On this page
os
Prev: optparse | Up: stdlib_module | Next: pathlib
Rel: pathlib, io, time, fileinput, stat
Ref: docs.python.org — os
Tags: #public #python3 #stdlib
Import
import os
Overview
Low-level operating system interface for environment variables, process state, permissions, file descriptors, and directory walking across POSIX and Windows. Prefer pathlib for path manipulation and subprocess for running external commands; reach for os when you need os.environ, os.scandir(), os.walk(), os.replace(), or process metadata.
Quick Start
import os
debug = os.getenv("DEBUG", "0") == "1"
cwd = os.getcwd()
cpu_count = os.cpu_count() or 1
assert isinstance(cwd, str) and cpu_count >= 1
Implementation Walkthrough
1. Fast Directory Traversal with os.scandir()
os.scandir() yields DirEntry objects that cache stat metadata from the OS directory listing, avoiding extra syscalls compared to os.listdir():
import os
def list_large_files(root: str, min_bytes: int = 1024) -> list[str]:
found = []
with os.scandir(root) as entries:
for entry in entries:
if entry.is_file(follow_symlinks=False) and entry.stat().st_size >= min_bytes:
found.append(entry.name)
return sorted(found)
2. Atomic File Replacement with os.replace()
Write to a sibling temporary file in the same directory and swap it into place atomically so readers never observe a half-written file:
import os
from pathlib import Path
def atomic_write(target: Path, content: str) -> None:
tmp = target.with_suffix(target.suffix + ".tmp")
tmp.write_text(content, encoding="utf-8")
os.replace(tmp, target) # atomic on POSIX and Windows (same filesystem)
Gotchas & Boundaries
- Never use
os.system()for external commands: It invokes a shell and invites command injection; usesubprocess.run([...])instead. - Avoid
os.chdir()in libraries or multithreaded code: Current working directory is process-global state; pass explicit paths instead. os.environvalues are always strings:os.environ["PORT"] = 8080raisesTypeError; convert withstr(...)and read defensively withos.getenv().os.replace()requires the same filesystem: Moving across mount points raisesOSError(EXDEV); useshutil.move()for cross-device moves.
Common Functions
- os.abort() —
abort()— Abort the interpreter immediately. - os.access() —
access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)— Use the real uid/gid to test for access to a path. - os.chdir() —
chdir(path)— Change the current working directory to the specified path. - os.chmod() —
chmod(...)— Change the access permissions of a file. - os.chown() —
chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)— Change the owner and group id of path to the numeric uid and gid. - os.close() —
close(fd)— Close a file descriptor. - os.cpu_count() —
cpu_count()— Return the number of logical CPUs in the system. - os.dup() —
dup(fd, /)— Return a duplicate of a file descriptor. - os.dup2() —
dup2(fd, fd2, inheritable=True)— Duplicate file descriptor. - os.fdopen() —
fdopen(fd, mode='r', buffering=-1, encoding=None, *args, **kwargs)—os.fdopen()function. - os.fork() —
fork()— Fork a child process. - os.fsdecode() —
fsdecode(filename)— Decode filename (an os.PathLike, bytes, or str) from the filesystem encoding with 'surrogateescape' error handler, return str unchanged. On Windows, use 'strict' error handler if the file system encoding is - os.fsencode() —
fsencode(filename)— Encode filename (an os.PathLike, bytes, or str) to the filesystem encoding with 'surrogateescape' error handler, return bytes unchanged. - os.fspath() —
fspath(path)— Return the file system path representation of the object. - os.getcwd() —
getcwd()— Return a unicode string representing the current working directory. - os.getenv() —
getenv(key, default=None)— Get an environment variable, return None if it doesn't exist. - os.getpid() —
getpid()— Return the current process id. - os.getppid() —
getppid()— Return the parent's process id. - os.kill() —
kill(pid, signal, /)— Kill a process with a signal. - os.link() —
link(...)— Create a hard link to a file. - os.listdir() —
listdir(path=None)— Return a list containing the names of the files in the directory. - os.lstat() —
lstat(path, *, dir_fd=None)— Perform a stat system call on the given path, without following symbolic links. - os.makedirs() —
makedirs(name, mode=511, exist_ok=False)— Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. If the target - os.mkdir() —
mkdir(path, mode=511, *, dir_fd=None)— Create a directory. - os.open() —
open(path, flags, mode=511, *, dir_fd=None)— Open a file for low level IO. Returns a file descriptor (integer). - os.pipe() —
pipe()— Create a pipe. - os.putenv() —
putenv(name, value, /)— Change or add an environment variable. - os.read() —
read(fd, length, /)— Read from a file descriptor. Returns a bytes object. - os.readlink() —
readlink(path, *, dir_fd=None)— Return a string representing the path to which the symbolic link points. - os.remove() —
remove(path, *, dir_fd=None)— Remove a file (same as unlink()). - os.removedirs() —
removedirs(name)— Super-rmdir; remove a leaf directory and all empty intermediate ones. Works like rmdir except that, if the leaf directory is successfully removed, directories corresponding to rightmost path - os.rename() —
rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)— Rename a file or directory. - os.replace() —
replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)— Rename a file or directory, overwriting the destination. - os.rmdir() —
rmdir(path, *, dir_fd=None)— Remove a directory. - os.scandir() —
scandir(path=None)— Return an iterator of DirEntry objects for given path. - os.stat() —
stat(path, *, dir_fd=None, follow_symlinks=True)— Perform a stat system call on the given path. - os.symlink() —
symlink(src, dst, target_is_directory=False, *, dir_fd=None)— Create a symbolic link pointing to src named dst. - os.system() —
system(command)— Execute the command in a subshell. - os.unlink() —
unlink(path, *, dir_fd=None)— Remove a file (same as remove()). - os.urandom() —
urandom(size, /)— Return a bytes object containing random bytes suitable for cryptographic use.
Classes & Objects
- os.DirEntry —
os.DirEntryclass. (Methods:.inode(),.is_dir(),.is_file(),.is_junction(),.is_symlink(),.stat()) - os.error — Base class for I/O related errors. (Methods:
.add_note(),.with_traceback()) - os.stat_result — stat_result: Result from stat, fstat, or lstat. (Methods:
.count(),.index()) - os.statvfs_result — statvfs_result: Result from statvfs or fstatvfs. (Methods:
.count(),.index()) - os.terminal_size — A tuple of (columns, lines) for holding terminal window size (Methods:
.count(),.index()) - os.times_result — times_result: Result from os.times(). (Methods:
.count(),.index()) - os.uname_result — uname_result: Result from os.uname(). (Methods:
.count(),.index()) - os.waitid_result — waitid_result: Result from waitid. (Methods:
.count(),.index())
Constants & Attributes
os.CLD_CONTINUED(int) =6os.CLD_DUMPED(int) =3os.CLD_EXITED(int) =1os.CLD_KILLED(int) =2os.CLD_STOPPED(int) =5os.CLD_TRAPPED(int) =4os.EX_CANTCREAT(int) =73os.EX_CONFIG(int) =78os.EX_DATAERR(int) =65os.EX_IOERR(int) =74os.EX_NOHOST(int) =68os.EX_NOINPUT(int) =66os.EX_NOPERM(int) =77os.EX_NOUSER(int) =67os.EX_OK(int) =0
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/argparse
- tuts/python3/stdlib_module/asyncio
- tuts/python3/stdlib_module/concurrent
- tuts/python3/stdlib_module/contextvars
- tuts/python3/stdlib_module/ctypes
- tuts/python3/stdlib_module/curses
- tuts/python3/stdlib_module/errno
- tuts/python3/stdlib_module/fcntl
- tuts/python3/stdlib_module/filecmp
- tuts/python3/stdlib_module/fileinput
- tuts/python3/stdlib_module/fnmatch
- tuts/python3/stdlib_module/genericpath
- tuts/python3/stdlib_module/getopt
- tuts/python3/stdlib_module/getpass
- tuts/python3/stdlib_module/glob
- tuts/python3/stdlib_module/grp
- tuts/python3/stdlib_module/io
- tuts/python3/stdlib_module/linecache
- tuts/python3/stdlib_module/logging
- tuts/python3/stdlib_module/mmap
- tuts/python3/stdlib_module/msvcrt
- tuts/python3/stdlib_module/multiprocessing
- tuts/python3/stdlib_module/nt
- tuts/python3/stdlib_module/ntpath
- tuts/python3/stdlib_module/optparse
- tuts/python3/stdlib_module/os/abort
- tuts/python3/stdlib_module/os/access
- tuts/python3/stdlib_module/os/chdir
- tuts/python3/stdlib_module/os/chmod
- tuts/python3/stdlib_module/os/chown
- tuts/python3/stdlib_module/os/close
- tuts/python3/stdlib_module/os/cpu_count
- tuts/python3/stdlib_module/os/DirEntry
- tuts/python3/stdlib_module/os/dup
- tuts/python3/stdlib_module/os/dup2
- tuts/python3/stdlib_module/os/error
- tuts/python3/stdlib_module/os/fdopen
- tuts/python3/stdlib_module/os/fork
- tuts/python3/stdlib_module/os/fsdecode
- tuts/python3/stdlib_module/os/fsencode
- tuts/python3/stdlib_module/os/fspath
- tuts/python3/stdlib_module/os/getcwd
- tuts/python3/stdlib_module/os/getenv
- tuts/python3/stdlib_module/os/getpid
- tuts/python3/stdlib_module/os/getppid
- tuts/python3/stdlib_module/os/kill
- tuts/python3/stdlib_module/os/link
- tuts/python3/stdlib_module/os/listdir
- tuts/python3/stdlib_module/os/lstat
- tuts/python3/stdlib_module/os/makedirs
- tuts/python3/stdlib_module/os/mkdir
- tuts/python3/stdlib_module/os/open
- tuts/python3/stdlib_module/os/pipe
- tuts/python3/stdlib_module/os/putenv
- tuts/python3/stdlib_module/os/read
- tuts/python3/stdlib_module/os/readlink
- tuts/python3/stdlib_module/os/remove
- tuts/python3/stdlib_module/os/removedirs
- tuts/python3/stdlib_module/os/rename
- tuts/python3/stdlib_module/os/replace
- tuts/python3/stdlib_module/os/rmdir
- tuts/python3/stdlib_module/os/scandir
- tuts/python3/stdlib_module/os/stat
- tuts/python3/stdlib_module/os/stat_result
- tuts/python3/stdlib_module/os/statvfs_result
- tuts/python3/stdlib_module/os/symlink
- tuts/python3/stdlib_module/os/system
- tuts/python3/stdlib_module/os/terminal_size
- tuts/python3/stdlib_module/os/times_result
- tuts/python3/stdlib_module/os/uname_result
- tuts/python3/stdlib_module/os/unlink
- tuts/python3/stdlib_module/os/urandom
- tuts/python3/stdlib_module/os/waitid_result
- tuts/python3/stdlib_module/pathlib
- tuts/python3/stdlib_module/platform
- tuts/python3/stdlib_module/posix
- tuts/python3/stdlib_module/posixpath
- tuts/python3/stdlib_module/pty
- tuts/python3/stdlib_module/pwd
- tuts/python3/stdlib_module/queue
- tuts/python3/stdlib_module/resource
- tuts/python3/stdlib_module/sched
- tuts/python3/stdlib_module/select
- tuts/python3/stdlib_module/selectors
- tuts/python3/stdlib_module/shutil
- tuts/python3/stdlib_module/signal
- tuts/python3/stdlib_module/socket
- tuts/python3/stdlib_module/ssl
- tuts/python3/stdlib_module/stat
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/subprocess
- tuts/python3/stdlib_module/syslog
- tuts/python3/stdlib_module/tempfile
- tuts/python3/stdlib_module/termios
- tuts/python3/stdlib_module/threading
- tuts/python3/stdlib_module/time
- tuts/python3/stdlib_module/tty
- tuts/python3/stdlib_module/winreg
Related notes
- tuts/python3/stdlib_module/fileinput Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/io Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/optparse Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/os/abort Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/os/access Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/os/chdir Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/os/chmod Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/os/chown Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/os/close Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/os/cpu_count Linked here; links to this page; shared tags: #stdlib