pythonpathlib

How to resolve a relative path, relative to any directory


I'm aware of how to resolve a relative path like '..\input\file\hello.txt' to an absolute path, relative to the current working directory:

from pathlib import Path

rel_path = Path(r'..\input\file\hello.txt')
print(f'Absolute path: {rel_path.absolute()}'

Output when cwd is C:\project\source\:

C:\project\source\..\input\file\hello.txt

And I also known to use .resolve() to fully resolve indirections:

from pathlib import Path

rel_path = Path(r'..\input\file\hello.txt')
print(f'Resolved path: {rel_path.resolve()}'

Output when cwd is C:\project\source\:

C:\project\input\file\hello.txt

How can I resolve a path relative to any path without changing the current working directory (if at all)? And even when I must change the current working directory, how can I fully resolve a path that doesn't actually exist? (since .resolve() only works for existing objects)

For example, using the imaginary get_relative_to():

get_relative_to(r'..\input\file\hello.txt', r'X:\bogus\folder')

Would ideally return 'X:\bogus\input\file\hello.txt'


Solution

  • Starting from version 3.6 resolve has an argument strict, when strict=False the path can be resolved even if it doesn't exist. Example tested in 3.8.0:

    from pathlib import Path
    
    
    def get_relative_to(path1, path2):
        return (path2 / path1).resolve(strict=False)
    
    
    print(
        get_relative_to(
            Path(r'..\input\file\hello.txt'),
            Path(r'X:\bogus\folder'),
        )
    )
    
    # X:\bogus\input\file\hello.txt