How to get an absolute file path in Python

前端 未结 9 1341
孤城傲影
孤城傲影 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:24

    import os
    os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))
    

    Note that expanduser is necessary (on Unix) in case the given expression for the file (or directory) name and location may contain a leading ~/(the tilde refers to the user's home directory), and expandvars takes care of any other environment variables (like $HOME).

提交回复
热议问题