Last modified: May 10, 2025 By Alexander Williams

Python OS Module: File System Operations Guide

The OS module in Python is a powerful tool for interacting with the operating system. It provides functions for file and directory operations.

This guide covers essential file system operations using the OS module. You'll learn how to work with files, directories, and paths.

Importing the OS Module

Before using the OS module, you need to import it. It's part of Python's standard library.

 
import os

For more on importing modules, see our guide on Python Import Statements Guide.

File Operations

The OS module provides functions for basic file operations. These include creating, renaming, and deleting files.

Creating Files

Use open() with write mode to create a file:

 
# Create a new file
with open('example.txt', 'w') as f:
    f.write('Hello, World!')

Renaming Files

The os.rename() function renames a file:

 
os.rename('example.txt', 'new_example.txt')

Deleting Files

Use os.remove() to delete a file:

 
os.remove('new_example.txt')

Directory Operations

The OS module also handles directory operations. You can create, list, and remove directories.

Creating Directories

Use os.mkdir() to create a single directory:

 
os.mkdir('new_folder')

For nested directories, use os.makedirs():

 
os.makedirs('parent/child/grandchild')

Listing Directory Contents

os.listdir() returns a list of files and directories:

 
contents = os.listdir('.')
print(contents)


['file1.txt', 'file2.py', 'new_folder']

Removing Directories

Use os.rmdir() to remove an empty directory:

 
os.rmdir('new_folder')

For non-empty directories, use shutil.rmtree() from the shutil module.

Path Operations

The OS module includes functions for working with file paths. These are cross-platform compatible.

Getting Current Directory

os.getcwd() returns the current working directory:

 
current_dir = os.getcwd()
print(current_dir)


/home/user/projects

Joining Paths

os.path.join() safely joins path components:

 
full_path = os.path.join('folder', 'subfolder', 'file.txt')
print(full_path)


folder/subfolder/file.txt

Checking Path Existence

os.path.exists() checks if a path exists:

 
if os.path.exists('file.txt'):
    print("File exists")

File Information

The OS module can retrieve information about files. This includes size, modification time, and permissions.

File Size

os.path.getsize() returns file size in bytes:

 
size = os.path.getsize('example.txt')
print(f"File size: {size} bytes")

File Modification Time

os.path.getmtime() returns last modification time:

 
import time
mtime = os.path.getmtime('example.txt')
print(f"Last modified: {time.ctime(mtime)}")

Advanced Operations

The OS module offers more advanced file system operations. These include walking directories and changing permissions.

Walking Directories

os.walk() generates directory tree information:

 
for root, dirs, files in os.walk('.'):
    print(f"Current directory: {root}")
    print(f"Subdirectories: {dirs}")
    print(f"Files: {files}")

Changing Permissions

os.chmod() changes file permissions:

 
# Make file readable by all
os.chmod('example.txt', 0o644)

Conclusion

The Python OS module is essential for file system operations. It provides cross-platform functions for files, directories, and paths.

You've learned basic and advanced operations. These include creating, listing, and modifying files and directories.

For more Python module techniques, check our guide on Importing Python Libraries.

Mastering the OS module will make your Python scripts more powerful. They can now interact with the file system effectively.