How to get an absolute file path in Python

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

    This always gets the right filename of the current script, even when it is called from within another script. It is especially useful when using subprocess.

    import sys,os
    
    filename = sys.argv[0]
    

    from there, you can get the script's full path with:

    >>> os.path.abspath(filename)
    '/foo/bar/script.py'
    

    It also makes easier to navigate folders by just appending /.. as many times as you want to go 'up' in the directories' hierarchy.

    To get the cwd:

    >>> os.path.abspath(filename+"/..")
    '/foo/bar'
    

    For the parent path:

    >>> os.path.abspath(filename+"/../..")
    '/foo'
    

    By combining "/.." with other filenames, you can access any file in the system.

提交回复
热议问题