Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...