如何创建一个传递给文件的python对象

时间:2016-11-02 23:28:34

标签: python file

我在Python中有一些行要传递一个函数,该函数由于某种原因只接受输入作为文件路径。例如,让s call this function func.read()`。

由于func.read()只知道如何读取文件而不是直接读取字符串,因此我被迫将文本写入辅助文件,然后将文件路径传递给func.read()

text="""some
random
text"""
fout = open("aux","wt")
fout.write(text)
fout.close()
func.read("aux")

但这很麻烦,我想避免依赖写外部文件。我可以修改函数来获取字符串或字符串列表,但这是最后一种情况(由于其他一些原因,我不能在这里详细介绍)。

有没有办法可以通过创建一个行为类似于文件路径的对象来“欺骗”此功能?基本上是一个可以传递给open()的对象我会说。

干杯

1 个答案:

答案 0 :(得分:0)

是的,duck typing。您可以创建一个看起来像文件对象的对象。

因为您只需要文件对象的read()方法,所以您可以创建一个也有read()方法的类。只需创建一个类的实例,并将其传递给依赖于read()的代码。无论那些依赖代码是什么,都会忽略这样一个事实:你给了它一个假的"文件对象。

以下是一个例子。

class FileImitator:
    def __init__(self, contents_of_file):
        self.contents_of_file = contents_of_file

    def read(self):
        return self.contents_of_file

这是一个期待文件对象的函数,但我会给它一个FileImitator的实例:

def read_from_file(file):
    print(file.read())

imitation_file = FileImitator("Great Scott!")

read_from_file(imitation_file)  # prints "Great Scott!"

当然,如果我想给它一个真正的文件对象,我也可以这样做:

def read_from_file(file):
    print(file.read())

real_file = open("/tmp/favorite-quotes.txt", "r")

read_from_file(real_file)  # prints out the contents of "favorite-quotes.txt"