ZetCode

Python pathlib

last modified November 17, 2026 Python 3.15

In this article we show how to work with files and directories in Python using the pathlib module.

The pathlib module from the standard library represents filesystem paths as objects. Instead of passing strings to functions from os, os.path, glob, and shutil, we call methods on a Path object and join paths with the / operator.

The module has two families of classes. Pure paths (PurePath, PurePosixPath, PureWindowsPath) only manipulate path strings and never touch the filesystem. Concrete paths (Path, PosixPath, WindowsPath) add I/O methods, such as exists, read_text, or mkdir. In practice we create Path objects; on Linux and macOS they are PosixPath instances, on Windows WindowsPath instances.

The examples are run in a directory that contains a few text files and a small project directory tree, shown in the Directory tree section. Most examples print relative paths, so the outputs do not depend on where the directory lives.

words.txt
blue
forest
sky
ocean
rabbit
clue

Several examples use this simple text file.

Creating paths

A Path is created from one or more strings or other paths. Paths are joined with the / operator or the joinpath method.

creating_paths.py
from pathlib import Path

p1 = Path('docs', 'guide', 'intro.md')
p2 = Path('docs') / 'guide' / 'intro.md'
p3 = Path('docs').joinpath('guide', 'intro.md')

print(p1)
print(p2)
print(p3)
print(p1 == p2 == p3)
print(repr(p1))

print(Path('docs//guide/./intro.md'))
print(Path('docs/../guide'))
print(Path('/etc') / '/usr' / 'lib')
print(Path())

The three ways of building the path produce equal objects. When printed, a path shows its string form; its representation shows the concrete class, here PosixPath.

Paths are normalized on creation: repeated slashes and . segments are removed. The .. segments are kept, because removing them could change the meaning of the path when symbolic links are involved. When an absolute path is joined, it replaces everything before it. An empty Path() is the current directory, ..

$ python creating_paths.py
docs/guide/intro.md
docs/guide/intro.md
docs/guide/intro.md
True
PosixPath('docs/guide/intro.md')
docs/guide/intro.md
docs/../guide
/usr/lib
.

Current directory, home, and the script directory

The Path.cwd class method returns the current working directory and Path.home the user's home directory. The __file__ variable holds the path of the running script.

cwd_home.py
from pathlib import Path

print(f'current directory: {Path.cwd()}')
print(f'home directory: {Path.home()}')
print(f'this script: {Path(__file__)}')

script_dir = Path(__file__).resolve().parent
words = script_dir / 'words.txt'

print(f'data file: {words}')
print(words.read_text().split())

Relative paths are resolved against the current working directory, which depends on where the program is started from. To load a data file stored next to the script, we build its path from Path(__file__).resolve().parent; this works from any working directory.

$ python cwd_home.py
current directory: /home/user/python
home directory: /home/user
this script: /home/user/python/cwd_home.py
data file: /home/user/python/words.txt
['blue', 'forest', 'sky', 'ocean', 'rabbit', 'clue']

Pure paths and Windows paths

Pure path classes work on any operating system. With PureWindowsPath, we can manipulate Windows paths on Linux, for instance paths read from a configuration file.

pure_paths.py
from pathlib import PurePosixPath, PureWindowsPath

win = PureWindowsPath('C:/Users/Jano/Downloads/wordpress-6.8.tar.gz')

print(win)
print(win.parts)
print(f'drive: {win.drive!r}, root: {win.root!r}, anchor: {win.anchor!r}')
print(win.as_posix())
print(PureWindowsPath(r'\\server\share\docs\a.txt').anchor)

print(PureWindowsPath('C:/Users') == PureWindowsPath('c:\\USERS'))
print(PurePosixPath('/home/user') == PurePosixPath('/home/USER'))

nix = PurePosixPath('/home/user/notes.txt')
print(nix.parts)
print(f'drive: {nix.drive!r}, root: {nix.root!r}, anchor: {nix.anchor!r}')

A path is split into components with parts. The drive is the drive letter or the UNC share, the root is the separator after it, and the anchor is the two together. The as_posix method returns the path with forward slashes.

Windows paths compare case-insensitively, POSIX paths case-sensitively. Python 3.15 removed the PurePath.is_reserved method, which checked for reserved Windows names such as NUL; the os.path.isreserved function (3.13, Windows only) replaces it.

$ python pure_paths.py
C:\Users\Jano\Downloads\wordpress-6.8.tar.gz
('C:\\', 'Users', 'Jano', 'Downloads', 'wordpress-6.8.tar.gz')
drive: 'C:', root: '\\', anchor: 'C:\\'
C:/Users/Jano/Downloads/wordpress-6.8.tar.gz
\\server\share\
True
False
('/', 'home', 'user', 'notes.txt')
drive: '', root: '/', anchor: '/'

Path components

A path has properties for its final component, the extension, and the parent directory.

components.py
from pathlib import Path

path = Path('/home/user/Downloads/wordpress-6.8.tar.gz')

print(f'name:     {path.name}')
print(f'stem:     {path.stem}')
print(f'suffix:   {path.suffix}')
print(f'suffixes: {path.suffixes}')
print(f'parent:   {path.parent}')
print(f'anchor:   {path.anchor}')
print(f'parts:    {path.parts}')

archive = Path('backup.tar.gz')
print(archive.suffixes)
print(archive.name.removesuffix(''.join(archive.suffixes)))

print(repr(Path('.bashrc').suffix), repr(Path('.bashrc').stem))
print(repr(Path('Makefile').suffix))

The name is the final component, the stem is the name without its last suffix, and the suffix is the last extension. The suffixes property lists all extensions, but it simply splits on dots: for wordpress-6.8.tar.gz, the version number yields a bogus .8 suffix.

For the backup.tar.gz archive, we remove all suffixes with removesuffix to get the bare name. A leading dot does not start a suffix, so .bashrc has an empty suffix, and so does Makefile.

$ python components.py
name:     wordpress-6.8.tar.gz
stem:     wordpress-6.8.tar
suffix:   .gz
suffixes: ['.8', '.tar', '.gz']
parent:   /home/user/Downloads
anchor:   /
parts:    ('/', 'home', 'user', 'Downloads', 'wordpress-6.8.tar.gz')
['.tar', '.gz']
backup
'' '.bashrc'
''

Parents

The parent property returns the logical parent of a path, and parents is a sequence of all ancestors.

parents.py
from pathlib import Path

path = Path('/home/user/Documents/reports/2026/q3.pdf')

print(path.parent)
print(path.parent.parent)

for parent in path.parents:
    print(f'  {parent}')

print(path.parents[0])
print(path.parents[2])
print(path.parents[-1])
print(path.parents[1:3])

print(list(Path('a/b/c.txt').parents))

The ancestors are listed from the nearest to the root. The parents sequence supports indexing, negative indexes, and slicing. The parents of a relative path end with .. These are purely lexical operations; the paths do not have to exist.

$ python parents.py
/home/user/Documents/reports/2026
/home/user/Documents/reports
  /home/user/Documents/reports/2026
  /home/user/Documents/reports
  /home/user/Documents
  /home/user
  /home
  /
/home/user/Documents/reports/2026
/home/user/Documents
/
(PosixPath('/home/user/Documents/reports'), PosixPath('/home/user/Documents'))
[PosixPath('a/b'), PosixPath('a'), PosixPath('.')]

Changing path components

Paths are immutable. The with_name, with_stem, and with_suffix methods return new paths with one component replaced.

with_methods.py
from pathlib import Path

path = Path('/home/user/reports/draft.txt')

print(path.with_name('final.txt'))
print(path.with_stem('summary'))
print(path.with_suffix('.md'))
print(path.with_suffix(''))
print(Path('data').with_suffix('.csv'))
print(Path('photo.JPG').with_suffix('.jpg'))

try:
    path.with_suffix('md')
except ValueError as e:
    print(f'ValueError: {e}')

try:
    Path('/').with_name('etc')
except ValueError as e:
    print(f'ValueError: {e}')

An empty string passed to with_suffix removes the suffix, and a path without a suffix gets one added. The new suffix must start with a dot. The with_name method fails on a path that has no name, such as the root directory.

$ python with_methods.py
/home/user/reports/final.txt
/home/user/reports/summary.txt
/home/user/reports/draft.md
/home/user/reports/draft
data.csv
photo.jpg
ValueError: Invalid suffix 'md'
ValueError: PosixPath('/') has an empty name

Absolute and resolved paths

The absolute method prefixes a relative path with the current directory. The resolve method also eliminates .. segments and follows symbolic links, producing the canonical path.

absolute_resolve.py
from pathlib import Path

rel = Path('project/../words.txt')

print(rel.is_absolute())
print(rel.absolute())
print(rel.resolve())
print(rel.resolve().is_absolute())

print(Path('~/notes.txt'))
print(Path('~/notes.txt').expanduser())

missing = Path('no/such/dir/../file.txt')
print(missing.resolve())

try:
    missing.resolve(strict=True)
except FileNotFoundError as e:
    print(f'FileNotFoundError: {e.strerror}')

The absolute method keeps the project/.. part, while resolve removes it. A tilde is not expanded automatically; we call expanduser. By default, resolve works on paths that do not exist, too; with strict=True it raises FileNotFoundError.

$ python absolute_resolve.py
False
/home/user/python/project/../words.txt
/home/user/python/words.txt
True
~/notes.txt
/home/user/notes.txt
/home/user/python/no/such/file.txt
FileNotFoundError: No such file or directory

Relative paths

The relative_to method computes a path relative to another path, and is_relative_to checks whether a path lies under another one.

relative.py
from pathlib import Path

archive = Path('/home/user/Downloads/wordpress-6.8.tar.gz')
home = Path('/home/user')

print(archive.relative_to(home))
print(archive.relative_to('/home'))
print(archive.is_relative_to(home))
print(archive.is_relative_to('/var'))

docs = Path('/home/user/Documents')

try:
    archive.relative_to(docs)
except ValueError as e:
    print(f'ValueError: {e}')

print(archive.relative_to(docs, walk_up=True))

The Downloads archive is not inside the Documents directory, so relative_to raises a ValueError. With walk_up=True (Python 3.12), the method may go up with .. segments. Like the other pure methods, relative_to does not consult the filesystem.

$ python relative.py
Downloads/wordpress-6.8.tar.gz
user/Downloads/wordpress-6.8.tar.gz
True
False
ValueError: '/home/user/Downloads/wordpress-6.8.tar.gz' is not in the subpath of '/home/user/Documents'
../Downloads/wordpress-6.8.tar.gz

Matching paths against patterns

Pure paths can be tested against glob-style patterns without touching the filesystem. The match method matches from the right, while full_match (Python 3.13) matches the whole path and supports the recursive ** wildcard.

matching.py
from pathlib import PurePath

path = PurePath('project/src/app/cli.py')

print(path.match('*.py'))
print(path.match('app/*.py'))
print(path.match('src/*.py'))

print(path.full_match('*.py'))
print(path.full_match('project/**/*.py'))
print(path.full_match('**/app/*.py'))
print(path.full_match('project/*/app/c?i.py'))

print(PurePath('README.MD').match('*.md'))
print(PurePath('README.MD').match('*.md', case_sensitive=False))

With match, the *.py pattern matches any path ending with a Python file, and src/*.py fails because the file is not directly under src. The full_match method needs a pattern for the whole path; ** matches any number of directories and ? one character. The case_sensitive option overrides the platform default.

$ python matching.py
True
True
False
False
True
True
True
False
True

Checking files

Concrete paths can query the filesystem. The exists, is_file, is_dir, and is_symlink methods return booleans and never raise an exception for missing paths.

file_checks.py
from pathlib import Path

Path('latest.txt').symlink_to('words.txt')
Path('broken.txt').symlink_to('nothing.txt')

paths = ['words.txt', 'project', 'missing.txt', 'latest.txt', 'broken.txt']

print(f'{"path":12} exists  file   dir    link')

for name in paths:
    p = Path(name)
    print(f'{name:12} {p.exists()!s:7} {p.is_file()!s:6} {p.is_dir()!s:6} {p.is_symlink()}')

print(Path('broken.txt').exists(follow_symlinks=False))
print(Path('latest.txt').readlink())
print(Path('latest.txt').samefile('words.txt'))

We create two symbolic links: latest.txt points to an existing file, broken.txt to a missing one. The checks follow symbolic links, so the broken link does not exist; with follow_symlinks=False (Python 3.12) exists checks the link itself. The readlink method returns the link target, and samefile checks whether two paths point to the same file.

$ python file_checks.py
path         exists  file   dir    link
words.txt    True    True   False  False
project      True    False  True   False
missing.txt  False   False  False  False
latest.txt   True    True   False  True
broken.txt   False   False  False  True
True
words.txt
True

Creating and removing directories

A directory is created with mkdir and an empty file with touch. Files are removed with unlink and empty directories with rmdir.

mkdir_touch.py
from pathlib import Path

base = Path('build')
base.mkdir()

try:
    base.mkdir()
except FileExistsError as e:
    print(f'FileExistsError: {e}')

base.mkdir(exist_ok=True)

nested = base / 'assets' / 'css'

try:
    nested.mkdir()
except FileNotFoundError as e:
    print(f'FileNotFoundError: {e}')

nested.mkdir(parents=True)
(nested / 'main.css').touch()
(base / 'index.html').touch()

for p in sorted(base.rglob('*')):
    print(p, 'dir' if p.is_dir() else f'{p.stat().st_size} bytes')

(base / 'index.html').unlink()
(base / 'index.html').unlink(missing_ok=True)
(nested / 'main.css').unlink()
nested.rmdir()

try:
    base.rmdir()
except OSError as e:
    print(f'{type(e).__name__}: {e.strerror}')

print(sorted(base.rglob('*')))

By default, mkdir fails if the directory exists or its parent is missing. The exist_ok=True option ignores an existing directory, and parents=True creates the missing parents. The unlink method raises FileNotFoundError for a missing file unless missing_ok=True is given. The rmdir method removes only empty directories; to delete a whole tree, use shutil.rmtree.

$ python mkdir_touch.py
FileExistsError: [Errno 17] File exists: 'build'
FileNotFoundError: [Errno 2] No such file or directory: 'build/assets/css'
build/assets dir
build/assets/css dir
build/assets/css/main.css 0 bytes
build/index.html 0 bytes
OSError: Directory not empty
[PosixPath('build/assets')]

Permissions of parent directories

The mode argument of mkdir applies only to the final directory; the parents created with parents=True get the default mode. Python 3.15 adds the parent_mode option, which sets the mode of the created parents.

parent_mode.py
import os
import stat
from pathlib import Path

os.umask(0o022)

Path('public/static/img').mkdir(parents=True)
Path('private/keys/ssh').mkdir(mode=0o700, parents=True, parent_mode=0o700)
Path('shared/cache/thumbs').mkdir(mode=0o755, parents=True, parent_mode=0o711)

for top in ('public', 'private', 'shared'):
    for p in [Path(top), *sorted(Path(top).rglob('*'))]:
        print(f'{stat.filemode(p.stat().st_mode)} {p}')

We set the umask to 022 so the output does not depend on the environment. The public directories get the default mode. All three private directories are accessible only by the owner. In the shared tree, the parents are traversable but not listable by others, while the final directory is readable. Before 3.15, the parents had to be created one by one to get a specific mode.

$ python parent_mode.py
drwxr-xr-x public
drwxr-xr-x public/static
drwxr-xr-x public/static/img
drwx------ private
drwx------ private/keys
drwx------ private/keys/ssh
drwx--x--x shared
drwx--x--x shared/cache
drwxr-xr-x shared/cache/thumbs

Reading and writing text

The write_text and read_text methods open the file, transfer the whole content, and close it. Always pass the encoding; without it, the locale encoding is used.

read_write_text.py
from pathlib import Path

path = Path('poem.txt')

text = 'Žltý kôň\nletí nad lúkou\n'
written = path.write_text(text, encoding='utf-8')

print(f'characters written: {written}')
print(f'file size in bytes: {path.stat().st_size}')

content = path.read_text(encoding='utf-8')
print(content, end='')
print(content.splitlines())

with path.open('a', encoding='utf-8') as f:
    f.write('a zmizne\n')

print(path.read_text(encoding='utf-8').splitlines())
print(path.read_bytes()[:10])

The write_text method returns the number of characters written. The file has more bytes than characters, because the accented Slovak letters take two bytes in UTF-8. The write_text method replaces the content; to append, we open the file in the a mode with the open method, which takes the same arguments as the built-in open.

$ python read_write_text.py
characters written: 24
file size in bytes: 30
Žltý kôň
letí nad lúkou
['Žltý kôň', 'letí nad lúkou']
['Žltý kôň', 'letí nad lúkou', 'a zmizne']
b'\xc5\xbdlt\xc3\xbd k\xc3\xb4'

Reading lines

For large files, we iterate over the file object returned by open line by line instead of reading everything at once.

read_lines.py
from pathlib import Path

path = Path('words.txt')

with path.open(encoding='utf-8') as f:
    for n, line in enumerate(f, 1):
        print(f'{n}: {line.rstrip()}')

words = path.read_text(encoding='utf-8').splitlines()
print(sorted(words, key=len))

The first part numbers the lines with enumerate. For small files, read_text().splitlines() gives a list of lines without the newline characters.

$ python read_lines.py
1: blue
2: forest
3: sky
4: ocean
5: rabbit
6: clue
['sky', 'blue', 'clue', 'ocean', 'forest', 'rabbit']

Merging two files

In the following example, we read two files given on the command line and merge them line by line.

adjectives.txt
blue
brown
strong
early
old

This is the adjectives.txt file.

nouns.txt
sky
cup
wind
snow
tree

This is the nouns.txt file.

merge_files.py
import sys
from pathlib import Path

fname1, fname2 = sys.argv[1:3]

data1 = Path(fname1).read_text(encoding='utf-8').splitlines()
data2 = Path(fname2).read_text(encoding='utf-8').splitlines()

for first, second in zip(data1, data2, strict=True):
    print(first, second)

We read both files into lists of lines and pair them with zip. The strict=True option raises a ValueError if the files have a different number of lines.

$ python merge_files.py adjectives.txt nouns.txt
blue sky
brown cup
strong wind
early snow
old tree

Binary files

Binary files, such as images, are read with read_bytes and written with write_bytes.

read_bytes.py
from pathlib import Path

path = Path('project/docs/img/logo.png')

data = path.read_bytes()

print(f'{path.name}: {len(data)} bytes')
print(data[:16].hex(' '))
print(data[:8] == b'\x89PNG\r\n\x1a\n')

width = int.from_bytes(data[16:20])
height = int.from_bytes(data[20:24])
print(f'image size: {width}x{height}')

copy = Path('logo_copy.png')
copy.write_bytes(data)
print(copy.read_bytes() == data)

We read a small PNG image and print its first 16 bytes in hexadecimal notation. Every PNG file starts with the same 8-byte signature, followed by the IHDR chunk with the image width and height as big-endian integers. Finally, we write a copy of the image and compare it with the original.

$ python read_bytes.py
logo.png: 463 bytes
89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52
True
image size: 16x16
True

Listing a directory

The iterdir method yields the entries of a directory as path objects, in arbitrary order and without the . and .. entries.

list_dir.py
from pathlib import Path

project = Path('project')

for entry in sorted(project.iterdir()):
    kind = 'dir ' if entry.is_dir() else 'file'
    print(f'{kind} {entry.name}')

dirs = [e.name for e in project.iterdir() if e.is_dir()]
files = [e.name for e in project.iterdir() if e.is_file()]
visible = [n for n in files if not n.startswith('.')]

print(sorted(dirs))
print(sorted(files))
print(sorted(visible))

We sort the entries and mark them as files or directories. The comprehensions split the entries into directories and files; hidden files, whose names start with a dot, are included, so we filter them out explicitly. For more ways to list directories, see Python list directory.

$ python list_dir.py
file .env
file README.md
dir  data
dir  docs
file main.py
file notes.txt
dir  src
dir  tests
['data', 'docs', 'src', 'tests']
['.env', 'README.md', 'main.py', 'notes.txt']
['README.md', 'main.py', 'notes.txt']

Globbing

The glob method yields the paths that match a pattern. The * wildcard matches any characters in a name, ? one character, and ** any number of directories. The rglob method is a recursive glob: rglob('*.py') equals glob('**/*.py').

globbing.py
from pathlib import Path

project = Path('project')

print(sorted(p.name for p in project.glob('*.md')))
print(sorted(str(p) for p in project.glob('*/*.md')))
print(sorted(str(p) for p in project.glob('**/*.py')))
print(sorted(str(p) for p in project.rglob('*.py')))
print(sorted(str(p) for p in project.glob('**/test_*.py')))
print(sorted(str(p) for p in project.glob('**/')))
print(sorted(p.name for p in project.rglob('*.txt')))
print(sorted(p.name for p in project.rglob('*.txt', case_sensitive=False)))
print(sorted(p.name for p in project.glob('.*')))

A pattern ending with a slash, **/, matches directories only, including the starting one. On Linux, globbing is case-sensitive, so *.txt misses REPORT.TXT until we pass case_sensitive=False (Python 3.12). Unlike the glob module, Path.glob matches hidden files with * patterns.

$ python globbing.py
['README.md']
['project/docs/guide.md', 'project/docs/index.md']
['project/main.py', 'project/src/app/__init__.py', 'project/src/app/cli.py', 'project/src/app/core.py', 'project/tests/test_core.py']
['project/main.py', 'project/src/app/__init__.py', 'project/src/app/cli.py', 'project/src/app/core.py', 'project/tests/test_core.py']
['project/tests/test_core.py']
['project', 'project/data', 'project/docs', 'project/docs/img', 'project/src', 'project/src/app', 'project/tests']
['notes.txt']
['REPORT.TXT', 'notes.txt']
['.env']

Directory tree

The following program prints the contents of a directory as an indented tree.

tree.py
from pathlib import Path


def tree(directory):
    print(f'{directory}/')

    for path in sorted(directory.rglob('*')):
        depth = len(path.relative_to(directory).parts)
        spacer = '    ' * depth
        suffix = '/' if path.is_dir() else ''
        print(f'{spacer}{path.name}{suffix}')


tree(Path('project'))

We sort all paths found by rglob('*'); sorting puts each directory before its contents. The depth of each entry is the number of parts of its path relative to the starting directory. The output shows the project tree used in this article.

$ python tree.py
project/
    .env
    README.md
    data/
        REPORT.TXT
        cities.csv
    docs/
        guide.md
        img/
            logo.png
        index.md
    main.py
    notes.txt
    src/
        app/
            __init__.py
            cli.py
            core.py
    tests/
        test_core.py

Walking a directory tree

The walk method (Python 3.12) is the pathlib counterpart of os.walk. For each directory, it yields the directory path and the lists of its subdirectory and file names.

walk.py
from pathlib import Path

for root, dirs, files in Path('project').walk():
    dirs.sort()
    size = sum((root / name).stat().st_size for name in files)
    print(f'{str(root):22} files: {len(files)}  bytes: {size:3}')

We print the number of files and their total size for every directory. Sorting the dirs list in place makes the walk visit the subdirectories in alphabetical order; removing names from it would skip those subdirectories.

$ python walk.py
project                files: 4  bytes: 120
project/data           files: 2  bytes:  71
project/docs           files: 2  bytes:  45
project/docs/img       files: 1  bytes: 463
project/src            files: 0  bytes:   0
project/src/app        files: 3  bytes: 111
project/tests          files: 1  bytes:  77

Counting files by extension

In the following example, we count the files in the project by their extension with collections.Counter.

count_files.py
from collections import Counter
from pathlib import Path

project = Path('project')

suffixes = Counter(p.suffix.lower() or '(none)'
                   for p in project.rglob('*') if p.is_file())

for suffix, count in sorted(suffixes.items(), key=lambda e: (-e[1], e[0])):
    print(f'{suffix:7} {count}')

The extensions are lowercased so that .TXT and .txt are counted together. Files without an extension are counted as (none); here it is the .env file. We sort by count and then by name, because most_common keeps ties in the order in which they were found.

$ python count_files.py
.py     5
.md     3
.txt    2
(none)  1
.csv    1
.png    1

File metadata

The stat method returns an os.stat_result object with the file size, modification time, permissions, and other metadata.

stat_table.py
from datetime import datetime
from pathlib import Path

project = Path('project')

files = sorted((p for p in project.rglob('*') if p.is_file()),
               key=lambda p: (-p.stat().st_mtime, p.as_posix()))

print(f'{"file":26} {"size":>5}  modified')

for p in files:
    st = p.stat()
    modified = datetime.fromtimestamp(st.st_mtime)
    name = p.relative_to(project).as_posix()
    print(f'{name:26} {st.st_size:5}  {modified:%Y-%m-%d %H:%M}')

total = sum(p.stat().st_size for p in files)
print(f'{len(files)} files, {total} bytes')

We list the project files from the most recently modified, with their sizes and modification times. The st_mtime attribute is a POSIX timestamp, which we convert with datetime.fromtimestamp. The as_posix method keeps forward slashes in the names on every platform.

$ python stat_table.py
file                        size  modified
notes.txt                     42  2026-11-17 08:15
README.md                     37  2026-11-16 14:32
src/app/core.py               42  2026-11-16 14:32
.env                           8  2026-11-10 09:00
docs/guide.md                 22  2026-11-10 09:00
docs/img/logo.png            463  2026-11-10 09:00
docs/index.md                 23  2026-11-10 09:00
main.py                       33  2026-11-10 09:00
src/app/__init__.py            0  2026-11-10 09:00
src/app/cli.py                69  2026-11-10 09:00
tests/test_core.py            77  2026-11-10 09:00
data/REPORT.TXT               10  2026-10-02 11:05
data/cities.csv               61  2026-10-02 11:05
13 files, 887 bytes

Copying and moving files

Python 3.14 added the copy, copy_into, move, and move_into methods. Before, these operations required the shutil module.

copy_move.py
from pathlib import Path

src = Path('words.txt')

copy = src.copy('words_backup.txt')
print(copy, copy.read_text() == src.read_text())

backup = Path('backup')
backup.mkdir()

print(src.copy_into(backup))
print(Path('project/docs').copy(backup / 'docs'))
print(sorted(str(p) for p in backup.rglob('*')))

moved = copy.move(backup / 'words_old.txt')
print(moved, copy.exists())

print(Path('nouns.txt').move_into(backup))
print(sorted(p.name for p in backup.iterdir()))

The copy method copies a file, or a whole directory tree, to the target path and returns the new path. The copy_into and move_into methods take a destination directory and keep the original name. The move method works like mv: it renames the file, or copies and deletes it when the target is on another filesystem.

$ python copy_move.py
words_backup.txt True
backup/words.txt
backup/docs
['backup/docs', 'backup/docs/guide.md', 'backup/docs/img', 'backup/docs/img/logo.png', 'backup/docs/index.md', 'backup/words.txt']
backup/words_old.txt False
backup/nouns.txt
['docs', 'nouns.txt', 'words.txt', 'words_old.txt']

Renaming files

The rename and replace methods rename a file or a directory and return the new path. A relative target is interpreted relative to the current directory, not to the original file's directory.

rename.py
from pathlib import Path

Path('draft.txt').write_text('first draft\n')
Path('final.txt').write_text('final version\n')

new = Path('draft.txt').rename('notes.txt')
print(new, Path('draft.txt').exists())

target = new.rename('final.txt')
print(target.read_text(), end='')

Path('a.txt').write_text('A\n')
Path('a.txt').replace('final.txt')
print(Path('final.txt').read_text(), end='')

On Linux and macOS, rename silently replaces an existing target, so the final.txt content is lost. On Windows, it raises FileExistsError instead. The replace method replaces the target on all platforms; use it when overwriting is intended.

$ python rename.py
notes.txt False
first draft
A

Path info

Python 3.14 added the info attribute. It answers the exists, is_dir, is_file, and is_symlink questions and caches the results.

path_info.py
from pathlib import Path

for entry in sorted(Path('project').iterdir()):
    info = entry.info
    kind = 'dir' if info.is_dir() else 'file' if info.is_file() else '?'
    print(f'{entry.name:10} {kind:4} exists={info.exists()} link={info.is_symlink()}')

print(type(Path('words.txt').info).__name__)

For paths yielded by iterdir, the info object reuses the file type data returned by the directory scan, so on most systems the checks need no extra system call per entry. The cache is never refreshed; for fresh results, call the methods on the path itself.

$ python path_info.py
.env       file exists=True link=False
README.md  file exists=True link=False
data       dir  exists=True link=False
docs       dir  exists=True link=False
main.py    file exists=True link=False
notes.txt  file exists=True link=False
src        dir  exists=True link=False
tests      dir  exists=True link=False
_Info

File URIs

The as_uri method converts an absolute path to a file: URI, and Path.from_uri (Python 3.13) converts a URI back to a path.

uri.py
from pathlib import Path

path = Path('/home/user/My Documents/čaj.txt')

uri = path.as_uri()
print(uri)
print(Path.from_uri(uri))
print(Path.from_uri(uri) == path)

try:
    Path('notes.txt').as_uri()
except ValueError as e:
    print(f'ValueError: {e}')

Spaces and non-ASCII characters are percent-encoded in the URI. Relative paths cannot be expressed as URIs. Since Python 3.14, calling as_uri on pure paths, such as PureWindowsPath, is deprecated; it remains available on concrete paths.

$ python uri.py
file:///home/user/My%20Documents/%C4%8Daj.txt
/home/user/My Documents/čaj.txt
True
ValueError: relative paths can't be expressed as file URIs

Creating an article

Content management systems often store articles in directories named after the year and month. The next program creates such a file from a title given on the command line.

new_article.py
import re
import sys
from datetime import date
from pathlib import Path

title = sys.argv[1]
slug = re.sub(r'[^a-z0-9]+', '-', title.lower()).strip('-')

today = date.today()
folder = Path('articles') / str(today.year) / f'{today.month:02}'
folder.mkdir(parents=True, exist_ok=True)

article = folder / f'{slug}.md'

if article.exists():
    sys.exit(f'already exists: {article}')

article.write_text(f'# {title}\n\n{today:%B %-d, %Y}\n', encoding='utf-8')

print(f'article created at: {article}')
print(article.read_text(encoding='utf-8'), end='')

The title is turned into a file name slug with a regular expression. The mkdir call with parents=True and exist_ok=True creates the year and month directories if needed and does nothing if they exist. The program refuses to overwrite an existing article; the second run exits with an error message.

$ python new_article.py "Python pathlib tips"
article created at: articles/2026/11/python-pathlib-tips.md
# Python pathlib tips

November 17, 2026
$ python new_article.py "Python pathlib tips"
already exists: articles/2026/11/python-pathlib-tips.md

Paths in other APIs

Most functions of the standard library accept path objects in place of strings. They implement the os.PathLike protocol: the __fspath__ method returns the string form.

fspath.py
import os
import shutil
import subprocess
from pathlib import Path

path = Path('project') / 'notes.txt'

with open(path, encoding='utf-8') as f:
    print(f.readline(), end='')

print(os.path.getsize(path))
print(os.fspath(path), type(os.fspath(path)).__name__)
print(str(path))

shutil.copy(path, Path('notes_copy.txt'))
print(subprocess.run(['wc', '-l', path], capture_output=True, text=True).stdout, end='')

The built-in open, the os.path functions, shutil, and subprocess all take Path objects. The os.fspath function returns the string form of a path-like object; str(path) gives the same result for paths.

$ python fspath.py
check the import order
42
project/notes.txt str
project/notes.txt
2 project/notes.txt

pathlib and os.path

The following table shows pathlib counterparts of common functions from the os, os.path, and shutil modules.

os and os.pathpathlib
os.path.join(a, b)Path(a) / b
os.getcwd()Path.cwd()
os.path.expanduser('~')Path.home()
os.path.abspath(p)p.absolute()
os.path.realpath(p)p.resolve()
os.path.basename(p)p.name
os.path.dirname(p)p.parent
os.path.splitext(p)p.stem, p.suffix
os.path.relpath(p, start)p.relative_to(start, walk_up=True)
os.path.exists(p)p.exists()
os.path.isfile(p), os.path.isdir(p)p.is_file(), p.is_dir()
os.path.getsize(p)p.stat().st_size
os.listdir(p)p.iterdir()
glob.glob('**/*.py', recursive=True)Path().glob('**/*.py')
os.walk(p)p.walk()
os.makedirs(p, exist_ok=True)p.mkdir(parents=True, exist_ok=True)
os.remove(p), os.rmdir(p)p.unlink(), p.rmdir()
os.rename(a, b), os.replace(a, b)a.rename(b), a.replace(b)
shutil.copy2(a, b), shutil.copytree(a, b)a.copy(b, preserve_metadata=True)
shutil.move(a, b)a.move(b)

The os functions are still useful in tight loops over many files, where creating path objects adds overhead, and for operations that pathlib does not cover, such as shutil.rmtree or os.chown.

Source

pathlib – Object-oriented filesystem paths

PEP 428 – The pathlib module

In this article we have worked with files and directories using the pathlib module. See also Python list directory, Python glob, Python shutil, Python read file, and Python os.walk.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.