Use the PurePath.relative_to() method to produce a relative path.

You weren't very clear as to how the base path is determined; here are two options:

Copysecondparent = path.parent.parent
homedir = pathlib.Path(r'C:\users\user1')

then just use str() on the path.relative_to(secondparent) or path.relative_to(homedir) result.

Demo:

Copy>>> import pathlib
>>> path = pathlib.Path(r'C:\users\user1\documents\importantdocuments')
>>> secondparent = path.parent.parent
>>> homedir = pathlib.Path(r'C:\users\user1')
>>> str(path.relative_to(secondparent))
'documents\\importantdocuments'
>>> str(path.relative_to(homedir))
'documents\\importantdocuments'
Answer from Martijn Pieters on Stack Overflow
🌐
Python
docs.python.org › 3 › library › pathlib.html
pathlib — Object-oriented filesystem paths
February 23, 2026 - pathlib implements path operations using PurePath and Path objects, and so it’s said to be object-oriented. On the other hand, the os and os.path modules supply functions that work with low-level str and bytes objects, which is a more procedural ...
Discussions

Help understanding relative paths in python
As you noticed, paths are relative to the working directory, not the Python file. ../data/input.txt This means one directory up, then data/input.txt. In the first example: project$ src/python main.py one directory up brings you outside of the project directory. The best way to handle paths is to specify the root directory. In your main.py file it would be: from pathlib import Path root_dir = Path(__file__).resolve().parent.parent Then later you would point to the text file like this: filename = root_dir / "data" / "input.txt" Edit: to clarify: Path(__file__) is a Path object for the Python file, resolve() makes it an absolute path, parent points to the directory the file is in (src), the next parent points one directory up (project). More on reddit.com
🌐 r/learnpython
4
5
December 7, 2022
pathlib's relative_to should behave like os.path.relpath
BPO 40358 Nosy @pitrou, @eryksun, @ammaraskar, @CuriousLearner, @CAM-Gerlach, @barneygale, @domragusa, @bowiechen PRs #19807#19813 Files relative_to.patch Note: these values reflect the state of th... More on github.com
🌐 github.com
17
April 22, 2020
Making paths absolute in os.path and pathlib - Core Development - Discussions on Python.org
On a POSIX system with symlinks, ... as the second ".." component is relative to the symlink target. This behaviour is called “plain wrong” in PEP 428[1]. If you answered "/home/me/../you/..", you’re in agreement with pathlib.Path.absolute...... More on discuss.python.org
🌐 discuss.python.org
4
January 15, 2024
python - How to find the relative path between two directories? - Stack Overflow
I would like to find the relative path between two directories on my system. Example: If I have pathA == and pathB == /dir1/dir2, the relative path between them will be... More on stackoverflow.com
🌐 stackoverflow.com
🌐
OneUptime
oneuptime.com › home › blog › how to use pathlib for file paths in python
How to Use pathlib for File Paths in Python
January 27, 2026 - # creating_paths.py # Different ways to create Path objects from pathlib import Path # From a string path1 = Path("/home/user/documents") # Current working directory cwd = Path.cwd() print(f"Current directory: {cwd}") # Home directory home = Path.home() print(f"Home directory: {home}") # Relative path relative = Path("data/output.csv") # From multiple parts path2 = Path("home", "user", "documents", "file.txt") # From the current file's location current_file = Path(__file__) project_root = current_file.parent.parent # Convert string to Path path_from_string = Path(some_string_path) # Convert Path to string path_string = str(path1)
🌐
Real Python
realpython.com › python-pathlib
Python's pathlib Module: Taming the File System – Real Python
January 11, 2025 - To do this, you first use .relative_to() to represent a path relative to the root directory. Then, you use the .parts property to count the number of directories in the representation.
🌐
Stack Abuse
stackabuse.com › introduction-to-the-python-pathlib-module
Introduction to the Python Pathlib Module
August 7, 2023 - An absolute path begins from the root directory and specifies the complete directory tree, whereas a relative path, as the name suggests, is the path of a file relative to another file or directory (usually the current directory). Directory represents the filesystem entry of the path and it ...
🌐
DataCamp
datacamp.com › tutorial › comprehensive-tutorial-on-using-pathlib-in-python-for-file-system-manipulation
How to Use Python's Pathlib (with Examples) | DataCamp
May 22, 2024 - In Unix-like systems, it is represented ... ... The parent contains the current file or directory. it is one level higher relative to the current directory or file....
Find elsewhere
🌐
LabEx
labex.io › home › modules › pathlib module
Python Pathlib Module - Python Cheatsheet
You can get a relative path from a starting path to another path. from pathlib import Path # Get relative path from base path print(Path('/etc/passwd').relative_to('/'))
🌐
GitHub
github.com › python › cpython › issues › 84538
pathlib's relative_to should behave like os.path.relpath · Issue #84538 · python/cpython
April 22, 2020 - pathlib's relative_to should behave like os.path.relpath#84538 · Copy link · Labels ·
Author   domragusa
🌐
Python Morsels
pythonmorsels.com › pathlib-module
Python's pathlib module - Python Morsels
November 18, 2024 - Note: The Path class returns an instance of either PosixPath or WindowsPath depending on whether your code is running on Windows. One of the most common path-related operations is to join path fragments together.
🌐
Python.org
discuss.python.org › core development
Making paths absolute in os.path and pathlib - Core Development - Discussions on Python.org
January 15, 2024 - On a POSIX system with symlinks, if os.getcwd() returns "/home/me", what is the absolute version of the relative path "../you/.."? If you answered "/home", you’re in agreement with os.path.abspath(). But if "/home/you" is a symlink to somewhere else in the filesystem, then your result is wrong, as the second ".." component is relative to the symlink target.
🌐
Note.nkmk.me
note.nkmk.me › home › python
How to Use pathlib in Python | note.nkmk.me
February 9, 2024 - You can create a Path object using the pathlib.Path() constructor by specifying a path string. It can be either a relative or an absolute path.
🌐
CodingNomads
codingnomads.com › python-path-and-pathlib
Python Path and `pathlib`
Relative path: This is the location, as seen from the directory, that your Python script executes from. Absolute path: This is the location from the root directory of your operating system.
🌐
Esri Community
community.esri.com › t5 › python-questions › how-to-set-relative-path-in-notebook › td-p › 1569694
Solved: How to set relative path in notebook - Esri Community
December 23, 2024 - from pathlib import Path import arcpy from arcpy._mp import Map # Get Project prj = arcpy.mp.ArcGISProject("CURRENT") # Set Paths home_folder = Path(prj.homeFolder) database: Path = home_folder / "Data.gdb" feature_class: Path = database / "FeatureClass" # Get Map _map: Map = prj.listMaps("Map Name")[0] # Add Featureclass _map.addDataFromPath(str(feature_class))
Top answer
1 of 4
42

The first section solves the OP's problem, though if like me, he really wanted the solution relative to a common root then the second section solves it for him. The third section describes how I originally approached it and is kept for interest sake.

Relative Paths

Recently, as in Python 3.4-6, the os.path module has been extended to accept pathlib.Path objects. In the following case however it does not return a Path object and one is forced to wrap the result.

foo = Path("C:\\foo")
baz = Path("C:\\baz")
Path(os.path.relpath(foo, baz))

> Path("..\\foo")

Common Path

My suspicion is that you're really looking a path relative to a common root. If that is the case the following, from EOL, is more useful

Path(os.path.commonpath([foo, baz]))

> Path('c:/root')

Common Prefix

Before I'd struck upon os.path.commonpath I'd used os.path.comonprefix.

foo = Path("C:\\foo")
baz = Path("C:\\baz")
baz.relative_to(os.path.commonprefix([baz,foo]))

> Path('baz')

But be forewarned you are not supposed to use it in this context (See commonprefix : Yes, that old chestnut)

foo = Path("C:\\route66\\foo")
baz = Path("C:\\route44\\baz")
baz.relative_to(os.path.commonprefix([baz,foo]))

> ...
> ValueError : `c:\\route44\baz` does not start with `C:\\route`

but rather the following one from J. F. Sebastian.

Path(*os.path.commonprefix([foo.parts, baz.parts]))

> Path('c:/root')

... or if you're feeling verbose ...

from itertools import takewhile
Path(*[set(i).pop() for i in (takewhile(lambda x : x[0]==x[1], zip(foo.parts, baz.parts)))])
2 of 4
11

Python 3.12 added the walk_up parameter to the Path.relative_to method. Now you can do:

>>> from pathlib import Path

>>> foo = Path.home() / 'foo'
>>> bar = Path.home() / 'bar'

>>> bar.relative_to(foo, walk_up=True)
PosixPath('../bar')
🌐
Python Forum
python-forum.io › thread-10595.html
Python 3.6.5 pathlib weird behaviour when resolve a relative path on root (macOs)
Hi, I have recently found a weird behaviour while trying to resolve a relative path located on the root directory on a macOs. I tried to resolve a Path('spam') and the interpreter answered PosixPath('//spam') —double slash for root— instead of ...
🌐
Alemoh Rapheal Baja
alemsbaja.hashnode.dev › demystifying-python-paths-a-comprehensive-guide-to-the-path-module-for-effortless-file-and-directory-management
Python path, pathlib in Python, os.path in Python
February 13, 2024 - Returns the path to the users (owner) directory of the current file or the target destination. from pathlib import Path Path.home() #C:\Users\Alemsbaja
🌐
Medium
medium.com › @balakrishna0106 › understanding-the-difference-between-a-relative-and-absolute-path-in-python-dca68d84139a
Understanding the Difference Between a Relative and Absolute Path in Python | by Balakrishna | Medium
September 17, 2024 - In this article, we will explain what relative and absolute paths are, how they work in Python, and provide examples to clarify the concept.