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
At a glance
- Purpose
- Scripting and general-purpose applications
- File extension
- .py
- Runs in
- Python interpreter
- Usually used with
- Python standard library and packages
Specifications & further reading
Related Python documentation
import
The import statement brings code from another module or package into the current file, letting you reuse functions, classes, and variables defined elsewhere - whether from Python's standard library, a third-party package, or your own project files. Python offers several import styles: importing an entire module, importing specific names directly, and renaming imports with 'as' to avoid naming conflicts or shorten long module names.if __name__ == '__main__'
Every Python module has a built-in __name__ variable. When a file is run directly, __name__ is set to '__main__'; when the same file is imported into another module, __name__ is set to the module's actual name instead. The if __name__ == '__main__': guard lets you write code that only runs when the file is executed directly, not when it's imported elsewhere - essential for writing reusable modules that also work as standalone scripts.File Handling
Python's built-in open() function reads from and writes to files on disk. Using it with the 'with' statement (a context manager) ensures the file is automatically closed when the block ends, even if an error occurs - this is the recommended way to work with files. The mode argument controls behavior: 'r' for reading, 'w' for writing (overwriting), 'a' for appending, among others.datetime Module
The datetime module provides classes for working with dates and times - creating them, formatting them for display, parsing them from text, and performing date arithmetic. The datetime class combines both a date and a time, while timedelta represents a duration, letting you add or subtract time spans from a date. strftime() formats a datetime as text, and strptime() parses text back into a datetime.
The import statement brings code from another module or package into the current file, letting you reuse functions, classes, and variables defined elsewhere - whether from Python's standard library, a third-party package, or your own project files. Python offers several import styles: importing an entire module, importing specific names directly, and renaming imports with 'as' to avoid naming conflicts or shorten long module names.if __name__ == '__main__'
Every Python module has a built-in __name__ variable. When a file is run directly, __name__ is set to '__main__'; when the same file is imported into another module, __name__ is set to the module's actual name instead. The if __name__ == '__main__': guard lets you write code that only runs when the file is executed directly, not when it's imported elsewhere - essential for writing reusable modules that also work as standalone scripts.File Handling
Python's built-in open() function reads from and writes to files on disk. Using it with the 'with' statement (a context manager) ensures the file is automatically closed when the block ends, even if an error occurs - this is the recommended way to work with files. The mode argument controls behavior: 'r' for reading, 'w' for writing (overwriting), 'a' for appending, among others.datetime Module
The datetime module provides classes for working with dates and times - creating them, formatting them for display, parsing them from text, and performing date arithmetic. The datetime class combines both a date and a time, while timedelta represents a duration, letting you add or subtract time spans from a date. strftime() formats a datetime as text, and strptime() parses text back into a datetime.