在 python c = pickle.load(open(fileName, 'r')) 中,这会关闭文件吗?

2024-04-09

我尝试谷歌但找不到答案。

如果我只是这样做

c = pickle.load(open(fileName, 'r'))

执行此操作后文件会自动关闭吗?


不,但您可以简单地调整它来关闭文件:

# file not yet opened
with open(fileName, 'r') as f:
    # file opened
    c = pickle.load(f)
    # file opened
# file closed

What with声明确实,是(除其他外)调用__exit__()中列出的对象的方法with语句(在本例中:打开的文件),在本例中关闭文件。

关于打开的文件__exit__() method:

>>> f = open('deleteme.txt', 'w')
>>> help(f.__exit__)
Help on built-in function __exit__:

__exit__(...)
    __exit__(*excinfo) -> None.  Closes the file.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 python c = pickle.load(open(fileName, 'r')) 中,这会关闭文件吗? 的相关文章

随机推荐