在内联"打开并写入文件"是close()隐式吗?

phi*_*ext 13 python file

在Python(> 2.7)中执行代码:

open('tick.001', 'w').write('test')
Run Code Online (Sandbox Code Playgroud)

结果与:

ftest  = open('tick.001', 'w')
ftest.write('test')
ftest.close()
Run Code Online (Sandbox Code Playgroud)

哪里可以找到有关此内联函数的'close'的文档?

Bra*_*des 23

close()当发生此file对象从存储器释放,因为它的缺失逻辑的一部分.因为在其他虚拟机的现代蟒蛇-像Java和.NET -当一个对象从内存中释放无法控制,它不再被认为是出色的Python到open()喜欢这个没有close().今天的建议是使用一个with语句,该语句明确请求close()退出块的时间:

with open('myfile') as f:
    # use the file
# when you get back out to this level of code, the file is closed
Run Code Online (Sandbox Code Playgroud)

如果您不需要f该文件的名称,则可以省略as该语句中的子句:

with open('myfile'):
    # use the file
# when you get back out to this level of code, the file is closed
Run Code Online (Sandbox Code Playgroud)