Python:文件对象冲突



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

谢谢你的回答,George

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是空的

好吧,您的诊断是正确的,而您的问题是您的用例是错误的。如果你真的想做你想做的事情,下面是它应该如何工作:

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

当然,这是一种方法,你可以用很多其他方法来解决。这个解决方案的美妙之处在于,当调用close()时,您的临时文件会被删除,这在您退出文件的上下文时发生。

当然,还有其他方法可以实现这一点,但我发现这是最简单、最明确的方法(当然,给method()一个明确的名称)。

HTH-

最新更新