在Python (>2.7)中,下面这段代码:
open('tick.001', 'w').write('test')
与以下代码具有相同的结果:
ftest = open('tick.001', 'w')
ftest.write('test')
ftest.close()
还有哪些文档可以找到关于这个内联功能的“close”方法的信息?
close()
在这里发生的时候,是在file
对象从内存中释放时作为其删除逻辑的一部分。因为现代Python在其他虚拟机上(如Java和.NET)不能控制对象何时从内存中释放,所以不再被认为是好的Python做法,没有close()
就使用open()
。今天的建议是使用with
语句,在退出块时显式请求close()
:
with open('myfile') as f:
# use the file
# when you get back out to this level of code, the file is closed
如果您不需要文件的名称f
,那么可以从语句中省略as
从句:
如果你不需要一个名字f
来命名文件,那么你可以在语句中省略as
从句:
with open('myfile'):
# use the file
# when you get back out to this level of code, the file is closed
f
的情况下进行内联操作? - kirill_igum.git/index.lock
文件来告诉其他应用程序不要干扰。它可以使用模式'x'
打开,以强制失败,如果文件已经存在的话。 - Brandon Rhodeswith
语句或显式的close
,没有提到当对象被释放时隐式关闭的情况。https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files - Brandon Rhodes