python - 使用 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
关键字来打开文件,以便不必显式关闭文件。这适用于这里的迭代器方法吗?
解决方案
尚未提及的内容:如果您只想读取或写入一些文本(或字节),那么在使用 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
推荐阅读
- c# - 构造前验证构造函数参数
- c# - 实体框架崩溃而不是使用 .NET 5 为重复记录引发异常
- kubernetes - 停止部署错误 Kubernetes 环境的方法
- java - 如何将两个矩阵相乘,一个 2D 乘以一个 1D?
- git - 如何将 msys2 与 git 分开运行?
- javascript - 如何制作用于创建二维类型对象数组的单线器?
- sql-server - 在 Visual Studio 中添加与服务器资源管理器的连接时用户登录失败
- powershell - 使用 Powershell 增加构建版本
- unity3d - 撞到东西后如何保持同样的速度?(统一二维)
- python - 创建 gensim 字典时添加进度条(详细)