os Module
The os
module is a built-in Python module that provides functions for interacting with the operating system in a portable manner, offering functions for file system operations, environment management, and process control. This built-in module acts as a bridge between Python programs and the underlying operating system, enabling cross-platform compatibility for system-level tasks.
The os
module is essential for tasks such as file manipulation, directory navigation, environment variable access, and system command execution. It abstracts operating system differences, allowing Python code to work consistently across Windows, macOS, and Linux platforms.
File and Directory Management
The os
module provides comprehensive functionality for managing files and directories, allowing developers to perform common filesystem operations programmatically.
os.getcwd()
: Returns the current working directory as a stringos.chdir()
: Changes the current working directory to the specified pathos.listdir()
: Returns a list of files and directories in the specified pathos.mkdir()
: Creates a single directoryos.makedirs()
: Creates a directory and all necessary parent directoriesos.remove()
: Deletes a file from the filesystemos.rmdir()
: Removes an empty directoryos.removedirs()
: Removes empty directories recursivelyos.rename()
: Renames a file or directoryos.replace()
: Renames with cross-platform overwrite capability
File/Directory Testing
The os.path
submodule offers functions to test and validate file and directory paths, providing essential information about filesystem objects.
os.path.exists()
: Checks if a file or directory exists at the specified pathos.path.isfile()
: Determines if a path points to a fileos.path.isdir()
: Determines if a path points to a directoryos.path.getsize()
: Returns the size of a file in bytesos.path.getmtime()
: Returns the last modification time of a file
Environment Variables
The os
module provides access to system environment variables, enabling programs to read configuration settings and system information.
os.environ
: A mapping object representing environment variablesos.getenv()
: Safely retrieves environment variables with optional default valuesos.putenv()
: Sets environment variables for the current process
Note: Be careful when changing environment variables, as these modifications can influence system behavior and security.
Process and System Info
The os
module offers functions to gather information about the current process and system, useful for system monitoring and cross-platform compatibility checks.
os.name
: Identifies the operating system platformos.uname()
: Returns detailed system information (Unix-only)os.getpid()
: Returns the current process IDos.getppid()
: Returns the parent process IDos.cpu_count()
: Returns the number of CPUs in the system
Running System Commands
The os
module provides capabilities for executing system commands and interacting with external programs from within Python scripts.
os.system()
: Executes system commands and returns the exit statusos.startfile()
: Opens files with associated applications (Windows-only)
The subprocess
module is generally preferred over os.system()
for production code as it offers better control, security, and flexibility for running external commands.
Permissions and Metadata
The os
module includes functions for managing file permissions and accessing detailed file metadata, which are essential for system administration tasks.
os.chmod()
: Changes file permissions using numeric mode valuesos.stat()
: Returns detailed file metadata including size, permissions, and timestamps
Syntax
import os
# File operations
os.function_name(path, [optional_parameters])
# Environment operations
os.environ[variable_name]
os.getenv(variable_name, [default_value])
# Process operations
os.function_name() # No parameters for info functions
Parameters:
path
: String representing file or directory pathvariable_name
: String representing the environment variable namedefault_value
: Optional default value if the environment variable doesn’t existoptional_parameters
: Function-specific parameters likeexist_ok
,mode
, etc.
Frequently Asked Questions
1. Is the os
module cross-platform compatible?
Yes, the os
module is designed to work across different operating systems, including Windows, macOS, and Linux. It abstracts platform-specific differences, though some functions like os.uname()
are Unix-specific and os.startfile()
is Windows-specific.
2. What’s the difference between os.path
and pathlib
?
While os.path
provides functions for path manipulation, the newer pathlib
module offers an object-oriented approach with more intuitive syntax. pathlib
is generally recommended for new projects, but os.path
remains widely used and fully supported.
3. Should I use os.system()
or subprocess
for running commands?
The subprocess
module is preferred over os.system()
for production code because it provides better security, error handling, and output capture capabilities. Use os.system()
only for simple, trusted commands.
os Module
- .basename()
- Returns the part of a pathname after the last forward-slash.
- .dirname()
- Returns the part of the pathname ranging from the start to the last forward-slash.
- .exists()
- Checks whether a given file or folder exists in the directory of an operating system.
- .join()
- Merges multiple path components into a single path using the appropriate file separator for the current operating system.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours