Tag: os

  • Exploring the Python os Module: A gateway to the Operating System

    Python is widely celebrated for its simplicity and power, and one of the key reasons behind its versatility is the vast collection of built-in modules. Among these, the os module stands out as a foundational tool for interacting with the operating system. Whether you’re managing files, navigating directories, or accessing system variables, the os module makes it easy to perform OS-level tasks directly from Python.

    What is the os module?

    The os module provides a way of using operating system-dependent functionality like reading or writing to the file system, modifying environment variables, or working with processes. It is a part of Python’s standard library, meaning you don’t need to install anything extra—just import it and you’re ready to go:

    Python
    import os

    Common use cases

    • Navigating the file system
    • Listing files and directories
    • Creating and removing directories
    • File manipulation
    • Working with paths
    • Environment variables

    Why use the os module?

    The os module abstracts away platform-specific details, allowing your scripts to run across Linux, Windows, and macOS without change. It helps automate workflows, manage resources, and build more powerful, adaptable applications.

    Files and Directory Operations

    Python
    os.getcwd()                  # Get current working directory
    os.chdir(path)               # Change current working directory
    os.listdir(path='.')         # List files and dirs
    os.mkdir(path, mode=0o777)   # Create directory
    os.makedirs(path, exist_ok=False)  # Create nested directories
    os.rmdir(path)               # Remove empty directory
    os.removedirs(path)          # Remove nested directories
    os.remove(path)              # Delete a file
    os.rename(src, dst)          # Rename/move file or dir
    os.replace(src, dst)         # Rename/move, overwrite if needed
    os.stat(path)                # Get file metadata
    os.scandir(path='.')         # Iterator of DirEntry objects
    os.walk(top)                 # Recursively list files/dirs

    Path Manipulation (os.path)

    Python
    os.path.join(a, b, ...)      # Join paths safely
    os.path.abspath(path)        # Absolute path
    os.path.basename(path)       # File name from path
    os.path.dirname(path)        # Directory from path
    os.path.exists(path)         # Path exists?
    os.path.isfile(path)         # Is file?
    os.path.isdir(path)          # Is directory?
    os.path.getsize(path)        # File size in bytes
    os.path.split(path)          # (dir, file)
    os.path.splitext(path)       # (filename, extension)

    Environment Variables

    Python
    os.environ                   # Dict-like env vars
    os.environ.get(key, default) # Get env var
    os.environ['VAR'] = value    # Set env var
    os.putenv(key, value)        # Set env var (less common)
    os.unsetenv(key)             # Remove env var

    Process Management

    Python
    os.system(command)           # Run shell command
    os.startfile(path)           # Open file/app (Windows)
    os.execv(path, args)         # Replace current process
    os.fork()                    # Create process (Unix)
    os.spawn*()                  # Start process (multiple variants)
    os.kill(pid, sig)            # Send signal to process
    os.getpid()                  # Current process ID
    os.getppid()                 # Parent process ID

    File Descriptor Ops (low-level)

    Python
    os.open(path, flags, mode=0o777) # Open file descriptor
    os.read(fd, n)                   # Read n bytes
    os.write(fd, b'some bytes')      # Write bytes
    os.close(fd)                     # Close file descriptor

    OS Info & Constants

    Python
    os.name               # 'posix', 'nt', 'java'
    os.sep                # Path separator ('/' or '\\')
    os.altsep             # Alt path sep (Windows)
    os.extsep             # Extension separator '.'
    os.pathsep            # PATH separator
    os.linesep            # Newline character(s)
    os.devnull            # Null device path
    os.cpu_count()        # Number of CPUs

    Miscellaneous

    Python
    os.urandom(n)         # n random bytes
    os.getlogin()         # Logged-in username
    os.getuid(), os.getgid()   # User/group ID (Unix)
    os.chmod(path, mode)  # Change permissions
    os.access(path, mode) # Check permissions