我编写了很多Python代码,我只想将文件读入变量.我知道推荐的两种方法是 -
with open('file') as f:
data = f.read()
# or
fo = open('file')
data = f.read()
fo.close()
Run Code Online (Sandbox Code Playgroud)
我的问题是,这有什么缺点?
data = open('file').read()
Run Code Online (Sandbox Code Playgroud)
Gre*_*ill 20
的缺点
data = open('file').read()
Run Code Online (Sandbox Code Playgroud)
这取决于您的Python实现,打开文件对象的清理可能会立即发生,也可能不会立即发生.这意味着文件将保持打开状态,消耗文件句柄.对于单个文件,这可能不是问题,但在循环中它肯定会有麻烦.
具体而言,CPython(通常的Python实现)使用引用计数对象,因此文件关闭几乎肯定会立即发生.但是,对于其他实现,例如IronPython或Jython,这不一定如此.
| 归档时间: |
|
| 查看次数: |
9838 次 |
| 最近记录: |