When using pathlib, getting error: TypeError: invalid file: PosixPath('example.txt')

When using pathlib, getting error: 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 accept os.PathLike objects, as have all relevant functions in the os and os.path modules, and most other functions and classes in the standard library.

要让它在 Python 3.5 和 Python 3.6 中工作,只需将对象转换为字符串:

contents = open(str(filename), "r").read()