Create Intermediate Directories if They Don’t Exist
os.remove("/path/to/file")
Remove a File
os.rmdir("/path/to/empty_directory")
Remove an Empty Directory
os.removedirs("/path/to/directory_to_remove")
Remove a Directory and Its Contents
File and Path Manipulation
Command
Description
os.path.join("/path", "to", "file_or_directory")
Join Paths
os.path.abspath("/path/to/file_or_directory")
Get the Absolute Path
os.path.basename("/path/to/file_or_directory")
Get the Base Name of a Path
os.path.dirname("/path/to/file_or_directory")
Get the Directory Name of a Path
os.path.split("/path/to/file_or_directory")
Split a Path into a Tuple (head, tail)
File Information
Command
Description
os.path.getsize("/path/to/file")
Get Size of a File
os.path.getmtime("/path/to/file")
Get Modification Time of a File
os.path.getctime("/path/to/file")
Get Creation Time of a File
time.ctime(modification_time)
Convert Modification Time to a Readable Format
Environmental Variables
Command
Description
os.getenv("MY_VARIABLE", default_value)
Get the Value of an Environment Variable
os.environ["MY_VARIABLE"] = "value"
Set an Environment Variable
os.environ.pop("MY_VARIABLE", None)
Removing an Environment Variable
Miscellaneous
Command
Description
os.system("command_to_execute")
Execute a Command in the Shell
os.name == 'nt'
Check if the Operating System is Windows
os.name == 'posix'
Check if the Operating System is POSIX (Linux, macOS)
By using these commands from the os module, you can improve your file and system operations in Python, making your code more robust and platform-independent. This cheat sheet serves as a quick reference for your the needs in the os module.