从历史上看我一直使用以下在读取文件python:
with open("file", "r") as f:
for line in f:
# do thing to line
Run Code Online (Sandbox Code Playgroud)
这仍然是推荐的方法吗?使用以下方法是否有任何缺点:
from pathlib import Path
path = Path("file")
for line in path.open():
# do thing to line
Run Code Online (Sandbox Code Playgroud)
我发现的大多数参考资料都使用with关键字来打开文件,以便不必明确关闭文件。这适用于这里的迭代器方法吗?