10/23/26About 3 minAbout 519 words
Concept: The os module
| Function / attribute | Description | Example |
|---|---|---|
| os.getcwd() | Returns the current working directory. | os.getcwd() β '/home/admin' |
| os.chdir(path) | Changes the current working directory. | os.chdir("/var/log") |
| os.listdir(path) | Returns a list with the names of the entries in a directory. | os.listdir("/etc") |
| os.walk(path) | Walks a directory tree recursively, yielding (dirpath, dirnames, filenames). | for root, dirs, files in os.walk("/var/log"): |
| os.mkdir(path) | Creates a single directory. | os.mkdir("backups") |
| os.makedirs(path, exist_ok=True) | Creates a directory and all missing parent directories. | os.makedirs("/tmp/a/b/c", exist_ok=True) |
| os.remove(path) | Deletes a file. | os.remove("old.log") |
| os.rmdir(path) | Deletes an empty directory. | os.rmdir("backups") |
| os.rename(src, dst) | Renames or moves a file or directory. | os.rename("app.log", "app.log.1") |
| os.chmod(path, mode) | Changes the permissions of a file (Unix-style octal mode). | os.chmod("script.py", 0o755) |
| os.stat(path) | Returns file metadata (size, owner, timestamps, permissions, ...). | os.stat("app.log").st_size |
| os.path.exists(path) | Checks whether a file or directory exists. | os.path.exists("/etc/hosts") β True |
| os.path.isfile(path) | Checks whether a path is an existing file. | os.path.isfile("/etc/hosts") β True |
| os.path.isdir(path) | Checks whether a path is an existing directory. | os.path.isdir("/etc") β True |
| os.path.abspath(path) | Converts a relative path to an absolute path. | os.path.abspath("script.py") β '/home/admin/script.py' |
| os.path.join(a, b, ...) | Joins path components using the correct separator for the OS. | os.path.join("/var", "log", "syslog") |
| os.path.basename(path) | Returns the last component of a path (the file name). | os.path.basename("/var/log/syslog") β 'syslog' |
| os.path.dirname(path) | Returns the directory part of a path. | os.path.dirname("/var/log/syslog") β '/var/log' |
| os.path.getsize(path) | Returns the size of a file in bytes. | os.path.getsize("app.log") β 20480 |
| os.environ | Dictionary-like object containing the environment variables. | os.environ["PATH"] |
| os.getenv(key, default=None) | Returns an environment variable, or the default if it doesn't exist. | os.getenv("HOME", "/tmp") |
| os.getpid() | Returns the process ID of the running script. | os.getpid() β 48213 |
| os.cpu_count() | Returns the number of logical CPUs. | os.cpu_count() β 8 |
| os.name | Name of the OS family: 'posix' (Linux/macOS) or 'nt' (Windows). | if os.name == "nt": |
| os.sep | The path separator of the OS: '/' or '\'. | os.sep β '/' |
| os.uname() | Returns system information (hostname, kernel release, architecture). Unix only. | os.uname().nodename β 'web01' |
| os.geteuid() | Returns the effective user ID; 0 means root. Unix only. | if os.geteuid() != 0: |