2014-02-16 56 views
0

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

谢谢您的回答, 乔治

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

我得到你正在寻找的['tempfile'(http://docs.python.org/2/library/tempfile.html)模块创建临时文件给你的感觉。但是从你的问题来看,并不清楚'file_path'和''foo.txt''来自哪里/他们代表什么。 –

+0

我可能是错的,但我认为临时文件不能解决我的问题。 Pyton可以从头开始创建一个文件对象(没有文件),或者使文件对象独立于支持它的文件? – GeorgeDean

+1

为什么每次执行'method'时都需要一个新的实例?通过这种方式,您必须解决文件访问同步,关闭临时文件等一些其他问题。 –

回答

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

+1

+1在'method'中没有返回'MyClass'的新实例,当然也是一个很好且有用的答案:) – danodonovan

+0

嗯,@danodonovan,你是对的,我倾向于忘记说明白:在良好的OOP中,唯一可以接受的方法是从方法中返回当前类的新实例,它来自类方法(又称静态方法),以实现工厂模式,否则您的设计是错误的! ;-) – zmo

+0

嘿,非常感谢您的回答。因为我需要在应用一个方法之前自己创建一个新实例,所以这些对象的处理有点复杂,但它可能更像这样“pythonic”。 但是,为了让你的解决方案正常工作,我需要在构造函数中添加一行'file.seek(0)',否则它会创建一个空对象:) – GeorgeDean