I have classes that can take a file as an argument, for example:
我有可以将文件作为参数的类,例如:
ParserClass(file('/some/file', 'rb'))
If I understand Python correctly, the file will be closed automatically once the object is garbage collected. What I don't understand is exactly when that happens. In a function like:
如果我正确理解Python,一旦对象被垃圾收集,该文件将自动关闭。我不明白的是,究竟何时会发生这种情况。在像这样的功能:
def parse_stuff(filename):
parser = ParserClasss(file(filename, 'rb'))
return list(parser.info())
Shouldn't that parser
object be GC'd immediately after the function exits, causing the file to be closed? Yet, for some reason, Python appears to have the file open long after the function exits. Or at least it looks that way because Windows won't let me modify the file, claiming Python has it open and forcing me to to close IDLE.
在函数退出后,该解析器对象不应该立即被GC'd,导致文件被关闭吗?然而,出于某种原因,Python似乎在函数退出后很长时间才打开文件。或者至少它看起来那样,因为Windows不会让我修改文件,声称Python打开它并迫使我关闭IDLE。
Is there a way to ensure files are closed, short of explicitly asking for it for every file I create? I also want to add that these classes are external, I don't want to dig through them to find out exactly what they with the file.
有没有办法确保文件被关闭,没有明确要求我创建的每个文件?我还想补充一点,这些类是外部的,我不想通过它们来深入了解它们与文件的对应关系。
2 个解决方案
#1
4
You can use with
to open files. When you use with
, the file will be implicitly closed when the with
block is exited, and it will handle exception states as well.
您可以使用with来打开文件。当你使用with时,文件将在退出with块时被隐式关闭,并且它也将处理异常状态。
#2
10
You can use the with
statement to open the file, which will ensure that the file is closed.
您可以使用with语句打开文件,这将确保文件已关闭。
with open('/some/file', 'rb') as f:
parser = ParserClasss(f)
return list(parser.info())
See http://www.python.org/dev/peps/pep-0343/ for more details.
有关详细信息,请参见http://www.python.org/dev/peps/pep-0343/。
#1
4
You can use with
to open files. When you use with
, the file will be implicitly closed when the with
block is exited, and it will handle exception states as well.
您可以使用with来打开文件。当你使用with时,文件将在退出with块时被隐式关闭,并且它也将处理异常状态。
#2
10
You can use the with
statement to open the file, which will ensure that the file is closed.
您可以使用with语句打开文件,这将确保文件已关闭。
with open('/some/file', 'rb') as f:
parser = ParserClasss(f)
return list(parser.info())
See http://www.python.org/dev/peps/pep-0343/ for more details.
有关详细信息,请参见http://www.python.org/dev/peps/pep-0343/。