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

2024-04-17 18:40:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python 3的^{}模块,如下所示:

from pathlib import Path

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

但我在一些机器上发现了这个错误:

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

但在我的机器上它能工作。


Tags: 模块pathfromimporttxt机器readexample
1条回答
网友
1楼 · 发布于 2024-04-17 18:40:33

^{}仅在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.

要使它在Python3.5和Python3.6中工作,只需将对象转换为字符串:

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

相关问题 更多 >

    热门问题