How to get an absolute file path in Python

前端 未结 9 1339
孤城傲影
孤城傲影 2020-11-22 11:53

Given a path such as \"mydir/myfile.txt\", how do I find the file\'s absolute path relative to the current working directory in Python? E.g. on Windows, I might

9条回答
  •  再見小時候
    2020-11-22 12:19

    Update for Python 3.4+ pathlib that actually answers the question:

    from pathlib import Path
    
    relative = Path("mydir/myfile.txt")
    absolute = relative.absolute()  # absolute is a Path object
    

    If you only need a temporary string, keep in mind that you can use Path objects with all the relevant functions in os.path, including of course abspath:

    from os.path import abspath
    
    absolute = abspath(relative)  # absolute is a str object
    

提交回复
热议问题