How to get an absolute file path in Python

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

    Today you can also use the unipath package which was based on path.py: http://sluggo.scrapping.cc/python/unipath/

    >>> from unipath import Path
    >>> absolute_path = Path('mydir/myfile.txt').absolute()
    Path('C:\\example\\cwd\\mydir\\myfile.txt')
    >>> str(absolute_path)
    C:\\example\\cwd\\mydir\\myfile.txt
    >>>
    

    I would recommend using this package as it offers a clean interface to common os.path utilities.

提交回复
热议问题