The os module in Python

The os module in Python provides a portable way to interact with the operating system, including Linux. While it doesn’t cover every aspect of Linux system administration, it offers functionalities for basic operations like file and directory manipulation, process management, and environment variables. Below are some of the key functions and classes in the os module:

  1. File and Directory Operations:
    • os.getcwd(): Get the current working directory.
    • os.chdir(path): Change the current working directory to the specified path.
    • os.listdir(path='.'): Return a list of the entries in the directory given by path.
    • os.mkdir(path): Create a directory named path.
    • os.makedirs(path): Recursive directory creation function.
    • os.remove(path): Remove (delete) the file path.
    • os.rmdir(path): Remove (delete) the directory path.
  2. Process Management:
    • os.system(command): Execute the command in a subshell.
    • os.spawn*(): Functions for spawning a new process.
    • os.fork(): Fork a child process.
    • os.kill(pid, sig): Send a signal to the process pid.
  3. Environment Variables:
    • os.environ: Dictionary containing the environment variables.
    • os.getenv(var, default=None): Get an environment variable, optionally returning a default value if the variable is not set.
  4. Miscellaneous:
    • os.path: Submodule for common pathname manipulations.
    • os.name: String representing the current operating system.
    • os.utime(path, times=None): Set the access and modified times of the file specified by path.
  5. Permissions:
    • os.chmod(path, mode): Change the mode (permissions) of path to the numeric mode.
    • os.access(path, mode): Check if a user has access to a file.

Remember, the os module provides basic functionalities. For more advanced operations, you might need to use other modules like subprocess, shutil, or os.path. Additionally, for system administration tasks on Linux, modules like subprocess, sys, shutil, socket, multiprocessing, and os.path are often used in conjunction with os.

Leave a comment