我正在使用 Python 3 的pathlib
模块,如下所示:
from pathlib import Path
filename = Path(__file__).parent / "example.txt"
contents = open(filename, "r").read()
但我在某些机器上收到此错误:
TypeError: invalid file: PosixPath('example.txt')
但在我的机器上它可以工作。
我正在使用 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
integrates seemlessly with open
only in Python 3.6 and later. From 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.
To get it to work in Python 3.5 and Python 3.6, just convert the object to a string:
contents = open(str(filename), "r").read()