About this articleThis article was generated using an automated workflow powered by generative AI. We reviewed the official Python pathlib specifications and validated relative path outputs and errors using a hypothetical directory structure.
Verification status: Code snippets have been executed in Python 3.12.14. Actual file creation and link-opening behaviors have not been verified.
Creating relative paths to sibling folders in Python's pathlib: relative_to and walk_up
reports/index.txt Suppose you want to write a relative path pointing to the adjacent charts/sales.png. In this case, you go up one level from the directory containing the document and enter charts, resulting in ../charts/sales.png. In Python 3.12 and later, pathlib allows you to calculate this path by passing relative_to() to walk_up=True.
The base is the directory containing the document
In this hypothetical layout, reports and charts are located directly under the same demo. The target is an image inside charts, and the base is reports. Setting the base to demo results in charts/sales.png and when that string is placed in reports/index.txt it points to reports/charts/sales.png First, verify which base location the reader of the output uses as a reference.
| Item | Example |
|---|---|
| Document recording relative paths | /demo/reports/index.txt |
| Directory containing the document | /demo/reports |
| Reference target | /demo/charts/sales.png |
| Path from the directory containing the document | ../charts/sales.png |
relative_to(base) Under the default behavior of , the subsequent part can be retrieved as a relative path only when the target is located under base. Requesting a path to a sibling directory causes ValueError to occur.walk_up=True When specifying , .. is included in the output if needed to return to the common parent.
Testing with Python 3.12
Save the following code as report_paths.py and run python3 report_paths.py in the terminal. In environments using the Python Launcher on Windows, you can also test with py -3.12 report_paths.py The demo is PurePosixPathBecause it uses , the path separator on Windows is also /It handles only path components and does not require actual folders or images to be created.
from pathlib import PurePosixPath, PureWindowsPath
document = PurePosixPath("/demo/reports/index.txt")
target = PurePosixPath("/demo/charts/sales.png")
try:
print(target.relative_to(document.parent))
except ValueError:
print("既定: ValueError")
print("兄弟:", target.relative_to(document.parent, walk_up=True))
print("共通の親:", target.relative_to(document.parent.parent, walk_up=True))
local_target = document.parent / "appendix" / "notes.txt"
print("配下:", local_target.relative_to(document.parent, walk_up=True))
try:
PureWindowsPath("D:/charts/sales.png").relative_to(
PureWindowsPath("C:/reports"), walk_up=True
)
except ValueError:
print("別ドライブ: ValueError")
The execution result is as follows.
既定: ValueError 兄弟: ../charts/sales.png 共通の親: charts/sales.png 配下: appendix/notes.txt 別ドライブ: ValueError
Even for the same file, if the base reference shifts by one level, the required number of .. changes. On the other hand, a appendix/notes.txt located under the same base does not need to traverse upward. In the final example, we use PureWindowsPath to verify, in an OS-independent manner, that relative paths cannot be created between different drives in Windows format.
What happens if we nest the document one level deeper?
document change only the value of /demo/reports/monthly/index.txt to ../../charts/sales.png and run the same program. Although the referenced image has not been moved, the sibling entry becomes monthly. Since the base has become .., the first-level reports returns to .., and the second-level demo returns to reports. The line displaying the "common parent" also changes to ../charts/sales.png because the base in the modified code becomes ... When reorganizing folders, recalculating from the base is easier to trace than manually adding
to the output.
walk_upcannot be used. First, check the Python version used for execution withpython3 --version. This argument was introduced in version 3.12. In environments with multiple Python installations, verify whether the interpreter selected by the editor matches the execution command in the terminal.ValueErroroccurs. Verify whether both the target and the base path are absolute paths or use the same format. Mixing different drives on Windows, or combining absolute and relative paths, cannot be made relative even withwalk_up=True. When distributing materials across different drives, arranging the file structure so that both the document and its references can be moved together allows them to be handled using relative paths.the result is shifted by one level. Inspect this by printing the base path passed to relative_to. The method call format is
target.relative_to(document.parent, walk_up=True). If you use adocumentcontaining the document name directly as the base, the code will treat that filename as part of the path.string is generated but cannot be opened. The code presented here does not check whether the path exists. When working with actual files, verify the filename, the layout after relocation, and the reference base of the path reader. In environments containing symbolic links where calculations are based on physical locations, the procedure for resolving the actual path using
Path.resolve(), as described in the official Python documentation, is relevant. Do not use the successful generation of a relative path as proof of access permissions to the reference or as verification that it resides within the folder.
The distinction in usage here is that when you need a path to navigate from a document to another folder, use walk_up=True, whereas if you only want to relativize when the target is strictly subordinate to the base, the default behavior should be used. In both cases, the starting point is determined by where the component actually consuming the relative path begins its traversal.
Official Documentation
- PurePath.relative_to in the Python 3.12 Official Documentation, covering the introduction of
walk_up, the generation of.., and the constraints regarding drives and symbolic links.
