Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
目前我正在使用此代码
if __name__=="__main__": try: main() except KeyboardInterrupt: f.close print "left!"
这是最好的方法吗?在脚本的早些时候,正在写入一个文件,我想确保在脚本终止时它完全关闭。请问有什么意见吗?
请注意:f.close实际上并没有关闭文件,您必须调用该函数:f.close()
f.close
f.close()
要回答您的问题,最好的方法是使用with块。即使引发异常,文件也会自动关闭:
with
with open('test.txt') as f: pass # Automatically closes file on with block exit