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

别等时光非礼了梦想. 提交于 2019-12-03 14:25:24

问题


I'm using Python 3's pathlib module, like this:

from pathlib import Path

filename = Path(__file__).parent / "example.txt"
contents = open(filename, "r").read()

But I get this error on some machines:

TypeError: invalid file: PosixPath('example.txt')

But on my machine it works.


回答1:


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.

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()


来源:https://stackoverflow.com/questions/42694112/when-using-pathlib-getting-error-typeerror-invalid-file-posixpathexample-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!