使用pathlib时,获取错误:TypeError:无效文件:PosixPath(' example.txt')

时间:2017-03-09 11:23:22

标签: 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')

但是在我的机器上它可以工作。

1 个答案:

答案 0 :(得分:40)

pathlib仅在Python 3.6及更高版本中与open无缝集成。来自Python 3.6's release notes

  

内置open()函数已更新为接受os.PathLike个对象,osos.path模块中的所有相关函数以及大多数其他函数和标准库中的类。

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

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