os & shutil#

os for operating system interfaces#

The os module of the Python Standard Library provides a wide interface to functionality that may depend on the operating system.

import os

os.environ["HOME"]          # access the $HOME environment variable
os.getenv("DEBUG", False)   # return the $DEBUG env var if set, or False as default
os.getpid()                 # get the current process ID
os.urandom(64)              # get 64 bytes of random data
os.chdir("data")            # change the current working directory

There’s a collection of methods to interact with file system paths. Even though they are still commonly used in many Python projects, new code should prefer the pathlib equivalents. Analogously the subprocess module should be preferred over the os.system() method to execute commands in a subshell.

shutil for high-level file operations#

The shutil module of the Python Standard Library offers helper functions for common file operations, like copying or deleting.

Below some usage examples, where source, dest and path are understood to be strings or path-like objects referring to files or directories.

import shutil

shutil.move(source, dest)       # mv source destination
shutil.copy(source, dest)       # cp source destination
shutil.copy2(source, dest)      # cp -p source destination
shutil.copytree(source, dest)   # cp -rp source destination
shutil.rmtree(path)             # rm -r path
shutil.which("python3")         # which python3
shutil.chown(path, user="jdoe", group="jdoe") # chown jdoe:jdoe path
shutil.diskusage(path)          # return total, used and free disk space