Search code examples
pythonpathlib

How to use pathlib to process paths that begin with ~?


I am writing a cli-tool that needs some path as input.

I am writing this tool in python and would like to use no python interpreter below 3.6. Using the packagepathlibseems to be the modern way to go when dealing with paths in python. So I would like to leave os and os.path behind if possible.

It seems like pathlib interprets the path ~/test/ as a relative path to the current working directory, the code below shows it

import pathlib

test_path = pathlib.Path('~/test')
absolute_path = test_path.absolute()

print(f"{str(test_path):>31}\n{str(absolute_path):>31}")
# output:
#              ~/test
# /home/myUser/~/test

How can I use pathlib to recognize every path starting with ~ as an absolute path and automatically expand ~ into the users home directory?


Solution

  • The answer is easy, use .expanduser() on your Path object instead of .absolute()and it will replace ~ with the home directory of the user running the script, the result is also an absolute path only if ~ is at the beginning:

    import pathlib
    
    test_path = pathlib.Path('~/test')
    absolute_path = test_path.expanduser()
    # If ~ is somewhere in the middle of the path, use .resolve() to get an absolute path.
    
    print(f"{str(test_path):>31}\n{str(absolute_path):>31}")
    # output:
    #            ~/test
    # /home/myUser/test