历史上,我一直使用以下方法读取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()
文档
还有一点没有提到:如果你只想读或写一些文本(或字节(,那么在使用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语句,原因与使用open
的上下文管理器相同,如文档所示:
>>> with path.open() as f:
... for line in f:
... print(line)
...
hello world
Path
对象用于处理文件系统路径。就像Python的内置库一样,Path对象中有一个open方法,但没有close。
.close
在文件句柄中,该句柄由内置的open或使用Path对象的open方法返回:
>>> from pathlib import Path
>>> p=Path(some_file)
>>> p
PosixPath('/tmp/file')
您可以使用内置的打开函数或Path对象中的打开方法打开Path对象:
>>> fh=open(p) # open built-in function
>>> fh
<_io.TextIOWrapper name='/tmp/file' mode='r' encoding='UTF-8'>
>>> fh.close()
>>> fh=p.open() # Path open method which aliases to os.open
>>> fh
<_io.TextIOWrapper name='/tmp/file' mode='r' encoding='UTF-8'>
>>> fh.close()
您可以在Github上查看pathlib的源代码,以了解pathlib
的作者如何在自己的代码中实现这一点。
我观察到的是三件事之一。
到目前为止,最常见的是使用with
:
from pathlib import Path
p=Path('/tmp/file')
#create a file
with p.open(mode='w') as fi:
fi.write(f'Insides of: {str(p)}')
# read it back and test open or closed
with p.open(mode='r') as fi:
print(f'{fi.read()} closed?:{fi.closed}')
# prints 'Insides of: /tmp/file closed?:False'
正如您可能知道的,在with
块的末尾会调用__exit__
方法。对于一个文件,这意味着该文件已关闭。这是pathlib
源代码中最常见的方法。
其次,您还可以在源代码中看到,pathlib对象维护一个进入和退出状态以及打开和关闭文件的标志。然而,os.close
函数并没有被显式调用。您可以使用.closed
访问器检查该状态。
fh=p.open()
print(f'{fh.read()} closed?:{fh.closed}')
# prints Insides of: /tmp/file closed?:False
# fi will only be closed when fi goes out of scope...
# or you could (and should) do fh.close()
with p.open() as fi:
pass
print(f'closed?:{fi.closed}')
# fi still in scope but implicitly closed at the end of the with bloc
# prints closed?:True
第三,在cPython上,当文件句柄超出范围时,文件将被关闭。这不是可移植的,也不被认为是可依赖的"好做法",但通常是这样。在pathlib源代码中有这样的实例。
Pathlib
是操作文件系统路径的面向对象方法。
使用pathlib模块打开文件的推荐方法是使用上下文管理器:
p = Path("my_file.txt")
with p.open() as f:
f.readline()
这样可以确保在文件使用后关闭该文件。
在您提供的两个示例中,您没有关闭文件,因为您在处打开了它们。
由于p.open()
返回文件对象,您可以通过分配它并检查属性closed
来测试它,如下所示:
from pathlib import Path
path = Path("file.txt")
# Open the file pointed by this path and return a file object, as
# the built-in open() function does.
f = path.open()
for line in f:
# do some stuff
print(f.closed) # Evaluates to False.