0
0
PythonHow-ToBeginner · 3 min read

How to Join Paths in Python: Simple Guide with Examples

In Python, you can join paths using the pathlib.Path.joinpath() method or the os.path.join() function. These methods combine parts of file paths into one complete path string that works across different operating systems.
📐

Syntax

There are two common ways to join paths in Python:

  • Using pathlib: Path.joinpath(*other) or the / operator.
  • Using os.path: os.path.join(path, *paths).

Both methods take one or more path parts and combine them into a single path string or Path object.

python
from pathlib import Path
import os

# Using pathlib
p = Path('folder')
full_path = p.joinpath('subfolder', 'file.txt')

# Using os.path
full_path_os = os.path.join('folder', 'subfolder', 'file.txt')
💻

Example

This example shows how to join folder and file names into a full path using both pathlib and os.path. It prints the resulting paths.

python
from pathlib import Path
import os

# Using pathlib
folder = Path('home')
file_path = folder / 'user' / 'document.txt'
print(f'Pathlib path: {file_path}')

# Using os.path
path_os = os.path.join('home', 'user', 'document.txt')
print(f'os.path path: {path_os}')
Output
Pathlib path: home/user/document.txt os.path path: home/user/document.txt
⚠️

Common Pitfalls

One common mistake is to join paths by simple string concatenation, which can cause errors or wrong paths on different systems. For example, using 'folder' + '/' + 'file.txt' may not work on Windows where the separator is \. Always use pathlib or os.path.join() to handle separators correctly.

python
import os

# Wrong way (string concatenation)
wrong_path = 'folder' + '/' + 'file.txt'
print(f'Wrong path: {wrong_path}')

# Right way
right_path = os.path.join('folder', 'file.txt')
print(f'Right path: {right_path}')
Output
Wrong path: folder/file.txt Right path: folder\file.txt
📊

Quick Reference

Here is a quick summary of path joining methods in Python:

MethodUsageNotes
pathlib.Path.joinpath()path.joinpath('subdir', 'file')Returns a new Path object, supports / operator
pathlib.Path / operatorpath / 'subdir' / 'file'Concise and readable, same as joinpath()
os.path.join()os.path.join('dir', 'file')Returns a string, works on all Python versions

Key Takeaways

Use pathlib.Path or os.path.join() to join paths safely across platforms.
Avoid string concatenation for paths to prevent errors with separators.
pathlib offers modern, readable syntax with the / operator.
os.path.join() returns strings and works well in older Python versions.
Joining paths correctly ensures your code works on Windows, macOS, and Linux.