Python:文件 - 对象冲突

时间:2014-02-16 15:40:04

标签: python file

我从python开始,我创建了一个从'file'类派生的文件对象类,以便能够操作大型数据文件。 我已经创建了特定的方法来处理这些文件,如下所示。 我需要在每个方法之后返回一个新的MyClass实例,以便能够继续处理它们。问题是,当我使用多次相同的方法时,与用作临时文件的文件foo.txt存在冲突,因为它仍然用作MyClass实例的支持。 有没有解决的办法 ?或者我是否需要为我的所有文件创建随机名称?

感谢您的回答, 乔治

Class MyClass(file):
    "Similar to open(file_path,'r')"
    def __init__(self,file_path):
        file.__init__(self,file_path)
    self.tell()

    def method(self):
        """Extract informations from self to write them in a temporary file foo.txt
        that will be used to return a new instance of MyClass"""
        output=open('foo.txt','w')
        self.seek(0)
        # Extracting information from self 
        output.write(information)
        output.close()
        return MyClass('foo.txt')

我已经完成了这个例子,使其更加清晰。我认为我的问题是我从我在方法中创建的文件中返回一个新的MyClass实例。如果我多次使用该方法而不关闭从foo.txt生成的实例,则实例变为空并返回“None”,因为重写了foo.txt。例如:

a=MyClass('/path/to/file')
b=a.method()
c=b.method()

然后返回错误,因为b为空

1 个答案:

答案 0 :(得分:1)

嗯,您的诊断是正确的,您的问题是您的用例错误。如果你想做你想要的事情,这就是它应该如何运作:

a=MyClass('/path/to/file')
a.method('/path/to/foo.txt')
b=MyClass('/path/to/foo.txt')
b.method('/path/to/bar.txt')
c=MyClass('/path/to/bar.txt')

这很简单,效果很好(当然,我不会详细介绍如何将参数赋予open())。虽然,它缺乏优雅。

要改进这一点,您可能需要创建唯一的临时文件,这样您就可以执行所需的操作:

a=MyClass('/path/to/file')
b=a.method()
c=b.method()

但问题是您仍然无法正确处理新创建/打开的临时文件。所以,你最好使用上下文管理器:

with open('/path/to/file') as a:
    with MyClass(a).method() as b:
        with MyClass(b).method() as c:
            # use a, b and c files here
            pass
# and now, a is closed, b and c are deleted.

所以当你不再需要它们时关闭文件:

import tempfile

Class MyClass():
    def __init__(self,file):
        self.file = file

    def method(self):
        """Extract informations from self to write them in a temporary file foo.txt
        that will be used to return a new instance of MyClass"""
        output = tempfile.TemporaryFile()
        self.seek(0)
        # Extracting information from self 
        output.write(information)
        return output

当然,这是一种做法,你可以通过许多其他方式解决这个问题。这个解决方案的优点在于你的temporary file gets deleted when you close() is called,当你退出文件的上下文时会发生这种情况。

当然,还有其他方法可以实现这一点,但我发现这是解决问题的最简单明了的方法(当然,鉴于你给method()明确的名称。)

HTH