在python c = pickle.load(open(fileName,'r'))中是否关闭文件? [英] In python c = pickle.load(open(fileName, 'r')) does this close the file?
本文介绍了在python c = pickle.load(open(fileName,'r'))中是否关闭文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用Google,但找不到答案.
I tried to Google but cannot find an answer.
如果我愿意
c = pickle.load(open(fileName, 'r'))
此操作后文件会自动关闭吗?
Will the file be automatically closed after this operation?
推荐答案
否,但是您可以简单地对其进行修改以关闭文件:
No, but you can simply adapt it to close the file:
# file not yet opened
with open(fileName, 'r') as f:
# file opened
c = pickle.load(f)
# file opened
# file closed
with
语句的作用是(除其他外)调用with
语句中列出的对象的__exit__()
方法(在本例中为打开的文件),在这种情况下将关闭文件.
What with
statement does, is (among other things) calling __exit__()
method of object listed in with
statement (in this case: opened file), which in this case closes the file.
关于打开文件的__exit__()
方法:
>>> f = open('deleteme.txt', 'w')
>>> help(f.__exit__)
Help on built-in function __exit__:
__exit__(...)
__exit__(*excinfo) -> None. Closes the file.
这篇关于在python c = pickle.load(open(fileName,'r'))中是否关闭文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文