python - 使用 pathlib 时,出现错误 : TypeError: invalid file: PosixPath ('example.txt' )

标签 python python-3.x pathlib

我正在使用 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 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()

关于python - 使用 pathlib 时,出现错误 : TypeError: invalid file: PosixPath ('example.txt' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42694112/

相关文章:

python - 当查询具有动态生成/可变长度参数列表时防止 SQL 注入(inject)

python - 如何使用 pathlib.Path().glob() 读入文件并将具有相同文件名的文件输出到另一个子文件夹

python - 如何使用 Pathlib 检查文件夹/文件权限

python - 我无法加载我的模型,因为我无法放置 PosixPath

python - 如何在 Django admin 中为一个模型制作单独的表单

python - 更改 Python Cmd 模块处理自动完成的方式

python - 如何使用 django 2 创建适应用户数量的表单?

python - 是否有 `pathos` 特定的方法来确定 CPU 核心数?

python - If 条件比较 Python 中的两个数据帧

python - 比较具有不同列名的两个 Pandas 数据框并找到匹配项