ZetCode

Python os module

last modified November 29, 2026 Python 3.15

In this article we show how to use the os module in Python.

The os module is a portable interface to the operating system. It provides functions for working with files and directories, file paths, environment variables, processes, and file descriptors. The same code runs on Linux, macOS, and Windows, although some functions exist only on some systems. The module is part of the standard library. Settings of the Python interpreter itself are in the sys module.

This article is an overview of the most used parts of the module. Many of the functions have their own articles, linked from the sections below and listed in the Python os API section of the Python tutorials index. For working with paths as objects, the pathlib module is usually more convenient. The examples work with a small project directory with a few text, Markdown, CSV, and Python files.

System information

The module has several functions and constants that describe the system and the current process.

system_info.py
import os

print(os.name)
print(os.uname().sysname, os.uname().machine)
print(os.cpu_count())
print(os.process_cpu_count())
print(os.getpid())
print(repr(os.sep), repr(os.linesep), repr(os.pathsep))
print(os.devnull)

The os.name attribute is posix on Unix-like systems and nt on Windows. The uname function returns the system name, release, and machine type; it is not available on Windows. The cpu_count function returns the number of CPUs in the system, while process_cpu_count, added in Python 3.13, returns the number of CPUs the current process may use. The getpid function returns the process ID. The sep, linesep, and pathsep constants are the path separator, the line ending, and the separator of directory lists such as PATH.

$ python system_info.py
posix
Linux x86_64
8
8
56669
'/' '\n' ':'
/dev/null

The current working directory

Relative paths are resolved against the current working directory. The getcwd function returns it and chdir changes it.

current_dir.py
import os

print(os.getcwd())

os.chdir('project')
print(os.getcwd())
print(os.path.exists('notes.txt'))

os.chdir('..')
print(os.getcwd())
print(os.path.exists('notes.txt'))

After changing to the project directory, the relative name notes.txt refers to the file in it. After returning to the parent directory, the same name refers to a file that does not exist. The current working directory and os.chdir articles go into more detail.

$ python current_dir.py
/home/user/os-module
/home/user/os-module/project
True
/home/user/os-module
False

Paths

The os.path module contains functions that work with path strings. Most of them only manipulate the text and do not touch the file system.

paths.py
import os

path = os.path.join('project', 'data', 'cities.csv')
print(path)

print(os.path.dirname(path))
print(os.path.basename(path))
print(os.path.split(path))
print(os.path.splitext(path))

print(os.path.abspath(path))
print(os.path.relpath('/usr/share/doc', '/usr/lib'))
print(os.path.normpath('project/./data/../docs/'))
print(os.path.expanduser('~/Documents'))

print(os.path.isfile(path), os.path.isdir(path))
print(os.path.getsize(path))

The join function joins path parts with the separator of the system. The dirname, basename, split, and splitext functions take a path apart. The abspath function prepends the current directory, relpath computes a relative path between two locations, and normpath removes redundant separators and . and .. parts. The expanduser function replaces the tilde with the home directory. The isfile, isdir, and getsize functions query the file system.

$ python paths.py
project/data/cities.csv
project/data
cities.csv
('project/data', 'cities.csv')
('project/data/cities', '.csv')
/home/user/os-module/project/data/cities.csv
../share/doc
project/docs
/home/user/Documents
True False
45

Listing a directory

The listdir function returns the names of the entries in a directory. The scandir function returns entry objects that also know the type and other information about each entry.

list_dir.py
import os

print(sorted(os.listdir('project')))
print()

with os.scandir('project') as entries:
    for entry in sorted(entries, key=lambda e: e.name):
        if entry.is_dir():
            print(f'{entry.name}/')
        else:
            print(f'{entry.name:<12} {entry.stat().st_size:>5} bytes')

Both functions return the entries in an arbitrary order, so we sort them. The special . and .. entries are not included. The scandir iterator is used in a with statement, which releases its resources. Each DirEntry has a name, a path, the is_dir and is_file methods, and a stat method; on most systems, the type checks need no extra system call. See Python list directory and os.scandir for more.

$ python list_dir.py
['Makefile', 'README.md', 'data', 'docs', 'main.py', 'notes.txt']

Makefile        21 bytes
README.md       59 bytes
data/
docs/
main.py         96 bytes
notes.txt       36 bytes

Walking a directory tree

The walk function visits a directory and all its subdirectories. For each directory it yields a tuple of the directory path, the names of its subdirectories, and the names of its files.

walk_tree.py
import os

for root, dirs, files in os.walk('project'):
    dirs.sort()
    depth = root.count(os.sep)
    indent = '    ' * depth

    print(f'{indent}{os.path.basename(root)}/')

    for name in sorted(files):
        print(f'{indent}    {name}')

The program prints the tree with indentation. The depth is the number of separators in the directory path. Sorting the dirs list in place changes the order in which walk visits the subdirectories; removing names from it would skip them. The os.walk article has more examples.

$ python walk_tree.py
project/
    Makefile
    README.md
    main.py
    notes.txt
    data/
        cities.csv
        rivers.csv
    docs/
        guide.md
        install.md

Creating and removing directories

The mkdir function creates one directory and makedirs creates a directory with all missing parents. The rmdir and removedirs functions remove empty directories.

directories.py
import os

os.mkdir('build')
os.makedirs('build/reports/2026/11', exist_ok=True)
os.makedirs('build/reports/2026/11', exist_ok=True)

for root, dirs, files in os.walk('build'):
    print(root)

try:
    os.mkdir('build')
except FileExistsError as e:
    print(e)

try:
    os.rmdir('build')
except OSError as e:
    print(e)

os.removedirs('build/reports/2026/11')
print(os.path.exists('build'))

With exist_ok=True, makedirs does nothing when the directory already exists, so the second call succeeds. Creating an existing directory with mkdir raises FileExistsError, and rmdir fails on a directory that is not empty. The removedirs function removes the leaf directory and then its parents as long as they are empty. To delete a whole tree with its files, use shutil.rmtree from the shutil module.

$ python directories.py
build
build/reports
build/reports/2026
build/reports/2026/11
[Errno 17] File exists: 'build'
[Errno 39] Directory not empty: 'build'
False

Renaming and removing files

The rename and replace functions rename or move a file, and remove deletes it.

files.py
import os

with open('draft.txt', 'w') as f:
    f.write('an old falcon\n')

os.rename('draft.txt', 'final.txt')
print(os.path.exists('draft.txt'), os.path.exists('final.txt'))

with open('backup.txt', 'w') as f:
    f.write('older text\n')

os.replace('final.txt', 'backup.txt')

with open('backup.txt') as f:
    print(f.read(), end='')

os.remove('backup.txt')
print(os.path.exists('backup.txt'))

try:
    os.remove('backup.txt')
except FileNotFoundError as e:
    print(e)

The replace function overwrites the target if it exists, so the contents of backup.txt are now the former final.txt. The rename function does the same on Unix but fails on Windows when the target exists, so replace is the portable choice for overwriting. Removing a file that does not exist raises FileNotFoundError. Copying files is done with the shutil module; see Python copy files.

$ python files.py
False True
an old falcon
False
[Errno 2] No such file or directory: 'backup.txt'

File information

The stat function returns information about a file: its size, permissions, owner, and times. The stat module helps to interpret the values.

file_info.py
import os
import stat
from datetime import datetime

info = os.stat('project/notes.txt')

print(f'size: {info.st_size} bytes')
print(f'mode: {stat.filemode(info.st_mode)} ({oct(info.st_mode & 0o777)})')
print(f'modified: {datetime.fromtimestamp(info.st_mtime):%Y-%m-%d %H:%M}')
print(f'regular file: {stat.S_ISREG(info.st_mode)}')

os.chmod('project/notes.txt', 0o600)
print(stat.filemode(os.stat('project/notes.txt').st_mode))

print(os.access('project/notes.txt', os.R_OK | os.W_OK))
print(os.access('/etc/shadow', os.R_OK))

The st_mtime attribute is the time of the last modification in seconds since the epoch. The st_mode attribute holds the file type and the permission bits; stat.filemode formats it like ls -l, and S_ISREG tests for a regular file. The chmod function changes the permissions, here to read and write for the owner only. The access function checks whether the current user may read or write a file. See os.stat and os.chmod for more.

$ python file_info.py
size: 36 bytes
mode: -rw-r--r-- (0o644)
modified: 2026-11-20 09:15
regular file: True
-rw-------
True
False

Environment variables

The environ mapping holds the environment variables of the process. The getenv function reads a variable with an optional default.

environment.py
import os

print(os.environ['HOME'])
print(os.environ.get('EDITOR', 'not set'))
print(os.getenv('APP_MODE', 'production'))

os.environ['APP_MODE'] = 'debug'
print(os.getenv('APP_MODE'))

os.system('echo "child sees $APP_MODE"')

del os.environ['APP_MODE']
print(os.getenv('APP_MODE'))

Reading a missing variable with square brackets raises KeyError, so get or getenv with a default is used for optional variables. Assigning to environ changes the environment of the current process and of the child processes it starts afterwards, as the echo command shows; the parent shell is not affected. In the second run, the variable is set on the command line for one command. See os.environ and os.getenv.

$ python environment.py
/home/user
not set
production
debug
child sees debug
None
$ APP_MODE=test python environment.py
/home/user
not set
test
debug
child sees debug
None

Running commands

The system function runs a command in a shell and waits for it to finish.

commands.py
import os

status = os.system('wc -l project/notes.txt project/main.py')
print(f'exit status: {status}')

status = os.system('ls missing 2> /dev/null')
print(f'exit status: {status}')
print(f'exit code: {os.waitstatus_to_exitcode(status)}')

The output of the command goes directly to the standard output. The function returns the wait status of the process; on Unix the exit code is stored in the high byte, so an exit code of 2 gives 512. The waitstatus_to_exitcode function extracts the exit code. For capturing output and passing arguments safely, the subprocess module is the better choice; see also Python execute command.

$ python commands.py
  3 project/notes.txt
  5 project/main.py
  8 total
exit status: 0
exit status: 512
exit code: 2

Low-level file I/O

The open, read, write, and close functions of the os module work with file descriptors, small integers that the operating system uses to identify open files.

low_level.py
import os

fd = os.open('log.txt', os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)
os.write(fd, b'first line\n')
os.write(fd, 'second line\n'.encode())
os.close(fd)

fd = os.open('log.txt', os.O_RDONLY)
print(os.read(fd, 5))
print(os.read(fd, 100))
print(os.read(fd, 100))
os.close(fd)

with os.fdopen(os.open('log.txt', os.O_RDONLY)) as f:
    print(f.readlines())

The flags of os.open select the access mode and options: write only, create the file, and truncate it. The third argument is the permission of a new file. The functions read and write bytes, not strings, and read returns at most the requested number of bytes, or an empty bytes object at the end of the file. The fdopen function wraps a descriptor in a regular file object. In most programs, the built-in open function is simpler; see Python read file.

$ python low_level.py
b'first'
b' line\nsecond line\n'
b''
['first line\n', 'second line\n']

Disk usage by file type

In the last example we walk the project directory and sum the sizes of the files by their extension.

disk_usage.py
import os
from collections import Counter


def disk_usage(top):
    sizes = Counter()
    counts = Counter()

    for root, dirs, files in os.walk(top):
        for name in files:
            ext = os.path.splitext(name)[1] or '(none)'
            sizes[ext] += os.path.getsize(os.path.join(root, name))
            counts[ext] += 1

    return sizes, counts


sizes, counts = disk_usage('project')

print(f'{"type":<8} {"files":>5} {"bytes":>6}')

for ext, size in sizes.most_common():
    print(f'{ext:<8} {counts[ext]:>5} {size:>6}')

print(f'{"total":<8} {counts.total():>5} {sizes.total():>6}')

The splitext function gives the extension; files without one, such as the Makefile, are counted under (none). The sizes are collected in Counter objects, whose most_common method lists the types from the largest, and total sums all counts.

$ python disk_usage.py
type     files  bytes
.md          3    139
.py          1     96
.csv         2     65
.txt         1     36
(none)       1     21
total        8    357

Source

Python os module documentation

Python os.path documentation

In this article we have used the os module to get system information, work with the current directory, paths, directories, and files, read file information, walk directory trees, use environment variables, run commands, and work with file descriptors. See also Python sys module, Python pathlib, Python shutil, and Python subprocess.

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.