Python `sys` and `os` Module Cheat Sheet


Python sys and os Module Cheat Sheet

sys Module

The sys module provides access to system-specific parameters and functions.

Command Line Arguments

We can read command line arguments using sys.argv.

import sys

print(sys.argv)  # Prints the list of command-line arguments

# Example usage:
# username = sys.argv[1]
# password = sys.argv[2]
# print(username, password)

os Module

The os module provides a way to interact with the operating system.

Listing Files and Getting the Current Directory

import os

print(os.listdir())  # List files in the current directory
print(os.getcwd())   # Get the current working directory

Changing Directories

os.chdir("D:\\")  # Change the current working directory to D:\

Environment Variables

print(os.getenv("python"))  # Get the value of an environment variable

Common os Functions

FunctionDescription
os.chdir(path)Change the current working directory
os.chmod(path, mode)Change file permissions
os.curdirRepresents the current directory symbol (.)
os.environDictionary of environment variables
os.getcwd()Get the current working directory
os.getenv(varname)Get the value of an environment variable
os.listdir(path)List files in the specified directory
os.makedirs(path, exist_ok=True)Create directories recursively
os.popen(command).read()Execute a shell command and get the output
os.rename(src, dst)Rename a file or directory
os.rmdir(path)Remove an empty directory
os.system(command)Execute a shell command
os.walk(path)Walk through a directory tree

Example Usage of os Module

import os  

os.chdir('D:\\')  # Change the current working directory  
os.chmod('file.txt', 0o644)  # Change file permissions  
print(os.curdir)  # Print current directory symbol (.)  
print(os.environ)  # Print environment variables  
print(os.getcwd())  # Get current working directory  
print(os.getenv('HOME'))  # Get value of an environment variable  
print(os.listdir('.'))  # List files in the current directory  
os.makedirs('new_folder/sub_folder', exist_ok=True)  # Create directories recursively  
print(os.popen('ls').read())  # Execute a shell command and get output  
os.rename('old.txt', 'new.txt')  # Rename a file  
os.rmdir('empty_folder')  # Remove an empty directory  
os.system('echo Hello')  # Execute a shell command  

# Walk through a directory tree
for root, dirs, files in os.walk('.'):  
    print(root, dirs, files)