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

前端 未结 1 793
孤城傲影
孤城傲影 2020-12-14 05:42

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

from pathlib import Path

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


        
相关标签:
1条回答
  • 2020-12-14 06:04

    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()
    
    0 讨论(0)
提交回复
热议问题