Syntax
import osExamples
Working with Paths
Joining and inspecting file paths in a cross-platform way.
import os
path = os.path.join("data", "reports", "summary.csv")
print(path) # data/reports/summary.csv (or data\\reports\\summary.csv on Windows)
print(os.path.exists(path)) # True or False
print(os.path.basename(path)) # summary.csv
print(os.path.dirname(path)) # data/reportsListing Directory Contents
Getting a list of files and folders within a directory.
import os
files = os.listdir(".") # current directory
print(files)
for name in os.listdir("."):
if os.path.isfile(name):
print(f"File: {name}")
elif os.path.isdir(name):
print(f"Directory: {name}")Environment Variables
Reading environment variables, commonly used for configuration like API keys.
import os
api_key = os.environ.get("API_KEY", "default-key")
print(api_key)
# Setting an environment variable for the current process
os.environ["DEBUG"] = "true"Creating and Removing Directories
Managing folders on the filesystem.
import os
os.makedirs("output/reports", exist_ok=True) # creates nested dirs, no error if they exist
print(os.path.exists("output/reports")) # True
os.rmdir("output/reports") # removes an empty directoryBest practices
- Use os.path.join() (or pathlib) instead of manually concatenating strings with "/" or "\\" for cross-platform compatibility
- Use os.environ.get(key, default) rather than os.environ[key] when a variable might not be set, to avoid a KeyError
- Use os.makedirs(path, exist_ok=True) instead of os.mkdir() when a path might have missing parent directories
- Consider pathlib.Path for new code - it offers a more modern, object-oriented API that many developers find more readable than os.path
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference