Python OS Operations
Python's os module provides a convenient way to interact with the operating system. It allows you to perform many common file system operations, such as creating, deleting, moving directories, and getting file information, etc. The os module is part of the Python standard library, so no additional installation is needed.
os Module vs os.path Submodule
osmodule: Mainly contains functions for interacting with the operating system itself, such as directory operations, process management, etc.os.pathmodule: Is a submodule ofosspecifically for handling file paths. Using functions fromos.pathensures your code has good portability across different operating systems (Windows, macOS, Linux) as it automatically handles issues like path separators (\or/).
Common os Module Functions
import os
# 1. Get Current Working Directory
current_dir = os.getcwd()
print(f"Current Directory: {current_dir}")
# 2. List files and subdirectories in a directory
# os.listdir('.') means list contents of current directory
print(f"Contents of current directory: {os.listdir('.')}")
# 3. Create directories
# os.mkdir('new_folder') # Create a single-level directory; raises error if it already exists
# os.makedirs('path/to/another_folder') # Create multi-level directories
# 4. Change current working directory
# os.chdir('new_folder')
# print(f"New Current Directory: {os.getcwd()}")
# os.chdir('..') # Return to parent directory
# 5. Delete files and directories
# with open('temp.txt', 'w') as f: f.write('temp')
# os.remove('temp.txt') # Delete a file
# os.rmdir('new_folder') # Delete an empty directory; raises error if not empty
# os.removedirs('path/to/another_folder') # Recursively delete empty directories
# 6. Rename file or directory
# os.rename('old_name.txt', 'new_name.txt')Common os.path Module Functions
Using os.path to handle paths is key to writing cross-platform code.
Path Joining: os.path.join()
This is the most important method for handling paths. It intelligently uses the correct path separator for your operating system to join one or more path components.
# On Windows this will be 'data\\files\\report.csv'
# On Linux/macOS this will be 'data/files/report.csv'
file_path = os.path.join('data', 'files', 'report.csv')
print(f"Joined path: {file_path}")Path Existence Checking
os.path.exists(path): ReturnsTrueif the path exists.os.path.isfile(path): ReturnsTrueif the path is an existing file.os.path.isdir(path): ReturnsTrueif the path is an existing directory.
print(f"Does '{file_path}' exist? {os.path.exists(file_path)}")
print(f"Is '.' a directory? {os.path.isdir('.')}")Path Splitting
os.path.basename(path): Returns the last part of the path (usually the filename).os.path.dirname(path): Returns everything except the last part of the path (usually the directory path).os.path.split(path): Splits the path into a tuple(dirname, basename).os.path.splitext(path): Splits the path into a tuple(root, ext), whereextis the file extension.
path = '/home/user/data/report.txt'
print(f"Basename: {os.path.basename(path)}") # report.txt
print(f"Dirname: {os.path.dirname(path)}") # /home/user/data
print(f"Split: {os.path.split(path)}") # ('/home/user/data', 'report.txt')
print(f"Splitext: {os.path.splitext(path)}") # ('/home/user/data/report', '.txt')Executing System Commands
The os.system(command) function can execute a shell command.
# Executes ls -l on Linux/macOS
# Executes dir on Windows
if os.name == 'nt': # 'nt' for Windows
os.system('dir')
else:
os.system('ls -l')Security Warning: Be very careful when using
os.system, especially when the command contains variables from user input, as this can lead to serious security vulnerabilities (command injection). For more complex subprocess management, using thesubprocessmodule is recommended.