首页 > 解决方案 > 使用 pathlib 模块关闭文件的推荐方法?

问题描述

从历史上看,我一直使用以下内容来读取文件python

with open("file", "r") as f:
    for line in f:
        # do thing to line

这仍然是推荐的方法吗?使用以下内容是否有任何缺点:

from pathlib import Path

path = Path("file")
for line in path.open():
    # do thing to line

我发现的大多数参考资料都使用with关键字来打开文件,以便不必显式关闭文件。这适用于这里的迭代器方法吗?

with open()文档

标签: pythonpython-3.xwith-statementpathlib

解决方案


尚未提及的内容:如果您只想读取或写入一些文本(或字节),那么在使用 pathlib 时您不再需要显式使用上下文管理器:

>>> import pathlib
>>> path = pathlib.Path("/tmp/example.txt")
>>> path.write_text("hello world")
11
>>> path.read_text()
'hello world'
>>> path.read_bytes()
b'hello world'

打开文件以迭代行仍应使用 with 语句,原因与使用上下文管理器 with 的所有原因相同open,如文档所示

>>> with path.open() as f:
...     for line in f:
...         print(line)
...
hello world

推荐阅读