os — process and filesystem interface

os and os.path helpers for joining paths, listing directories, and renaming files in a temporary directory, without reading the user environment or home directory.

模块页正文目前为英文。

The os module provides the operating-system interface: process helpers, directory listing, and path strings via os.path. It is a standard-library module, not a third-party package. Object-oriented path construction and Path.read_text live on the pathlib page; this page does not repeat those Path APIs.

File examples use tempfile.TemporaryDirectory and never print that path. They do not read the process environment, the home directory, or any other user file. listdir and walk return names in an arbitrary order, so examples sort before printing. Path separators below were measured on POSIX (macOS). This page does not invent Windows backslash output. Official documentation notes that os.rename raises if the destination exists on Windows, while os.replace overwrites the destination when permitted; that Windows rename case is not measured here.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

os.path join and split

os.path.join inserts the official os.path.sep between segments. Empty segments are handled in a platform-specific way; the examples use ordinary relative parts. os.path.split cuts at the final separator, and os.path.splitext cuts at the final suffix. These functions work on strings and do not require the path to exist. For a Path object with parts, name, and suffix, see pathlib.

os.path.join, os.path.split, os.path.basename, os.path.splitext

os.path.join(path, *paths)
os.path.split(path)
os.path.basename(path)
os.path.splitext(path)

Join path segments and split a path into directory, file name, or suffix. These helpers operate on strings and do not open files.

ParameterDescription
path, pathsPath segments or a path string. join inserts the current operating system separator.

Returns: join returns a single path string. split returns (head, tail). basename returns the final component. splitext returns (root, ext), where ext includes the leading dot or is empty.

  • The slash-separated results were measured on POSIX (macOS). They are not Windows output.
  • The list of names from listdir is covered in the next section because it requires a real directory.
python
import os

print(os.path.join("home", "ada", "src.py"))
print(os.path.split(os.path.join("sub", "b.txt")))
print(os.path.basename("sub/b.txt"), os.path.splitext("b.txt"))

Expected output

home/ada/src.py
('sub', 'b.txt')
b.txt ('b', '.txt')

Related: pathlib.Path

Official documentation →

listdir, stat, rename, and errors

os.makedirs creates intermediate directories. os.listdir returns the names in a directory, in an arbitrary order, without "." or "..". os.stat returns metadata such as st_size. os.rename renames a file; os.remove deletes a file. A missing path raises FileNotFoundError. os.mkdir raises FileExistsError if the directory already exists. The example reports those types and does not assert operating-system error text. TemporaryDirectory removes the directory when the block ends.

os.makedirs, os.listdir, os.stat, os.rename, os.remove, os.mkdir

os.makedirs(name, mode=0o777, exist_ok=False)
os.listdir(path=None)
os.stat(path, *, dir_fd=None, follow_symlinks=True)
os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
os.remove(path, *, dir_fd=None)
os.mkdir(path, mode=0o777, *, dir_fd=None)

Create a temporary tree, list it in sorted order, rename and remove a file, and catch FileNotFoundError and FileExistsError by type.

ParameterDescription
name / path / src / dstFilesystem paths inside TemporaryDirectory. The example never prints the temporary root and never reads a user file.

Returns: listdir returns a list of names. stat returns a stat_result; st_size is the size in bytes. mkdir, makedirs, rename, and remove return None on success.

Raises

  • FileNotFoundError — Raised by stat (and other calls) when the path does not exist. The example prints the exception type name, not the OS message.
  • FileExistsError — Raised by mkdir when the directory already exists. makedirs(..., exist_ok=True) would not raise in that case.
  • listdir is officially in an arbitrary order. The example sorts the names so the output is deterministic.
  • On POSIX, rename may replace an existing file. Official documentation says that on Windows, rename raises if the destination exists and os.replace is the portable overwrite. That Windows case is not measured here.
python
import os
import tempfile

with tempfile.TemporaryDirectory(prefix="os-ref-") as base:
    os.makedirs(os.path.join(base, "sub"))
    path = os.path.join(base, "note.txt")
    with open(path, "w", encoding="utf-8") as file:
        file.write("hi")
    print(sorted(os.listdir(base)))
    print(os.stat(path).st_size)
    os.rename(path, os.path.join(base, "renamed.txt"))
    print("renamed.txt" in os.listdir(base), "note.txt" in os.listdir(base))
    try:
        os.stat(os.path.join(base, "missing.txt"))
    except FileNotFoundError as err:
        print(type(err).__name__)
    try:
        os.mkdir(os.path.join(base, "sub"))
    except FileExistsError as err:
        print(type(err).__name__)
    os.remove(os.path.join(base, "renamed.txt"))
    print("renamed.txt" in os.listdir(base))

Expected output

['note.txt', 'sub']
2
True False
FileNotFoundError
FileExistsError
False

Related: pathlib read and write

Official documentation →