Skip to content

Python pathlib Path Operations Error Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Python pathlib Path Operations Error Fix. We cover key concepts, practical examples, and best practices.

Python's pathlib.Path raises errors like "FileNotFoundError", "NotADirectoryError", "PermissionError", or returns unexpected results when paths use wrong separators, the file does not exist, or the current working directory is not what you expect.

The Problem

from pathlib import Path

path = Path('data/config.json')
with open(path) as f:
    data = f.read()

Error:

FileNotFoundError: [Errno 2] No such file or directory: 'data/config.json'

Wrong Code

from pathlib import Path

# WRONG — relative path depends on current working directory
path = Path('config.json')
if path.exists():
    data = path.read_text()

# WRONG — using string concatenation for paths
base = Path('/app')
full = Path(str(base) + '//' + 'data' + '\\' + 'file.txt')

Right Code

from pathlib import Path

# Use PurePath.joinpath for clean path joining
base = Path('/app')
path = base / 'data' / 'config.json'
# OR: path = base.joinpath('data', 'config.json')

if path.exists():
    data = path.read_text()
    print(f"Read {len(data)} characters from {path}")
else:
    print(f"File not found: {path}")

Expected output:

Read 1234 characters from /app/data/config.json

Step-by-Step Fix

Step 1: Use absolute paths

from pathlib import Path

# Get absolute path of script directory
script_dir = Path(__file__).parent.resolve()
config_path = script_dir / 'config.json'

# Or use explicit absolute path
config_path = Path('/etc/myapp/config.json')

Step 2: Check existence properly

path = Path('data.txt')

# Check if it exists
if path.exists():
    print("File exists")

# Check if it is a file (not a directory)
if path.is_file():
    print("Is a file")

# Check if it is a directory
if path.is_dir():
    print("Is a directory")

Step 3: Use correct path joining

from pathlib import Path

# RIGHT — use / operator
base = Path('/app')
config = base / 'config' / 'settings.json'

# RIGHT — use joinpath
config = base.joinpath('config', 'settings.json')

# WRONG — string concatenation
config = Path(str(base) + '/config/settings.json')

Step 4: Read and write files

from pathlib import Path

path = Path('data.txt')

# Read text
content = path.read_text(encoding='utf-8')

# Write text
path.write_text('Hello, World!', encoding='utf-8')

# Read bytes
data = path.read_bytes()

# Write bytes
path.write_bytes(b'binary data')

Step 5: Handle cross-platform paths

from pathlib import Path, PureWindowsPath, PurePosixPath

# Convert between platforms
linux_path = PurePosixPath('/home/user/file.txt')
windows_path = PureWindowsPath(linux_path)
print(windows_path)  # \home\user\file.txt

# Use the platform's native separator
home = Path.home()
config = home / '.config' / 'myapp' / 'config.json'

Step 6: List directory contents

from pathlib import Path

dir_path = Path('/app')

# List all files
for f in dir_path.iterdir():
    print(f.name)

# List only Python files
for f in dir_path.glob('*.py'):
    print(f.name)

# List recursively
for f in dir_path.rglob('*.py'):
    print(f.relative_to(dir_path))

Prevention Tips

  • Use Path(__file__).parent.resolve() to get the script directory
  • Always check path.exists() before reading
  • Use / operator for path joining (cleaner than joinpath)
  • Use read_text() / write_text() instead of open()
  • Use rglob for recursive file searches

Common Mistakes with pathlib error

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between Path and PurePath?

Path creates concrete paths for the current operating system and supports system calls (exists, read, write, mkdir). PurePath creates platform-independent path objects for manipulation only — no filesystem access. Use PurePosixPath for Linux paths on Windows.

How do I create directories with pathlib?

Use path.mkdir(parents=True, exist_ok=True) to create a directory and all parent directories. Without parents=True, mkdir fails if the parent does not exist. Without exist_ok=True, it fails if the directory already exists.

Why does path.exists() return False for a file I know exists?

The path is relative and the current working directory is not what you expect. Use Path(__file__).parent / 'filename' to reference files relative to the script, or print Path.cwd() to see the current working directory. Also check for permission issues.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro