How to resolve relative paths in python?

后端 未结 4 990
遇见更好的自我
遇见更好的自我 2021-02-18 12:57

I have Directory structure like this

projectfolder/fold1/fold2/fold3/script.py

now I\'m giving script.py a path as commandline argument of a fi

相关标签:
4条回答
  • 2021-02-18 13:16
    import os
    dir = os.path.dirname(__file__)
    path = raw_input()
    if os.path.isabs(path):
        print "input path is absolute"
    else:
        path = os.path.join(dir, path)
        print "absolute path is %s" % path
    

    Use os.path.isabs to judge if input path is absolute or relative, if it is relative, then use os.path.join to convert it to absolute

    0 讨论(0)
  • 2021-02-18 13:16

    A practical example:

    sys.argv[0] gives you the name of the current script

    os.path.dirname() gives you the relative directory name

    thus, the next line, gives you the absolute working directory of the current executing file.

    cwd = os.path.abspath(os.path.dirname(sys.argv[0]))

    Personally, I always use this instead of os.getcwd() since it gives me the script absolute path, independent of the directory from where the script was called.

    0 讨论(0)
  • 2021-02-18 13:27

    try os.path.abspath, it should do what you want ;)

    Basically it converts any given path to an absolute path you can work with, so you do not need to distinguish between relative and absolute paths, just normalize any of them with this function.

    Example:

    from os.path import abspath
    filename = abspath('../../fold_temp/myfile.txt')
    print(filename)
    

    It will output the absolute path to your file.

    EDIT:

    If you are using Python 3.4 or newer you may also use the resolve() method of pathlib.Path. Be aware that this will return a Path object and not a string. If you need a string you can still use str() to convert it to a string.

    Example:

    from pathlib import Path
    filename = Path('../../fold_temp/myfile.txt').resolve()
    print(filename)
    
    0 讨论(0)
  • 2021-02-18 13:30

    For Python3, you can use pathlib's resolve functionality to resolve symlinks and .. components.

    You need to have a Path object however it is very simple to do convert between str and Path.

    I recommend for anyone using Python3 to drop os.path and its messy long function names and stick to pathlib Path objects.

    0 讨论(0)
提交回复
热议问题