os

The Python os module provides tools for using operating system-dependent functionality, like reading or writing to the file system. It allows you to interface with the underlying operating system in a portable way.

Here’s an example:

Python
>>> import os
>>> os.name
'posix'

Key Features

  • Interacts with the operating system
  • Manipulates file paths and directories
  • Provides access to environment variables
  • Facilitates process management

Frequently Used Classes and Functions

Object Type Description
os.path Module Provides common pathname manipulations
os.environ Mapping Gives access to environment variables
os.listdir() Function Lists directory contents
os.mkdir() Function Creates a directory
os.remove() Function Removes a file
os.rename() Function Renames a file or directory
os.walk() Function Generates file names in a directory tree

Examples

List the contents of a directory:

Python
>>> os.listdir("path/to/target/directory")

Create and remove a directory:

Python
>>> os.mkdir("new_dir")

>>> os.rmdir("new_dir")

If the directory doesn’t exist or isn’t empty, then rmdir() raises a FileNotFoundError or an OSError, respectively.

Access an environment variable:

Python
>>> os.environ["HOME"]
'/home/realpython'

Common Use Cases

  • Navigating and manipulating the file system
  • Manipulating file and directory paths
  • Managing environment variables
  • Running shell commands from Python scripts
  • Iterating over files and directories

Real-World Example

Say that you want to organize a directory by moving all .txt files into a subdirectory called text_files. You can achieve this using the os module:

Python
>>> import os
>>> os.makedirs("text_files", exist_ok=True)

>>> for filename in os.listdir("."):
...     if filename.endswith(".txt"):
...         os.rename(filename, os.path.join("text_files", filename))
...

>>> os.listdir("text_files")
['file1.txt', 'file2.txt']

In this example, you use the os module to create a new directory and move text files into it, which helps keep the file system organized.

Tutorial

Python's pathlib Module: Taming the File System

Python's pathlib module enables you to handle file and folder paths in a modern way. This built-in module provides intuitive semantics that work the same way on different operating systems. In this tutorial, you'll get to know pathlib and explore common tasks when interacting with paths.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated July 16, 2025