我正在使用 Python 3 的 pathlib
模块,像这样:
from pathlib import Path
filename = Path(__file__).parent / "example.txt"
contents = open(filename, "r").read()
但我在某些机器上收到此错误:
TypeError: invalid file: PosixPath('example.txt')
但在我的机器上它可以工作。
最佳答案
pathlib
仅在 Python 3.6 及更高版本中与 open
无缝集成。来自 Python 3.6's release notes :
The built-in
open()
function has been updated to acceptos.PathLike
objects, as have all relevant functions in theos
andos.path
modules, and most other functions and classes in the standard library.
要让它在 Python 3.5 和 Python 3.6 中工作,只需将对象转换为字符串:
contents = open(str(filename), "r").read()
关于python - 使用 pathlib 时,出现错误 : TypeError: invalid file: PosixPath ('example.txt' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42694112/