all Python 3Files & I/Oterm
os
os
The os module is the interface to the operating system: files, directories and environment variables.
Syntax
import os
os.getcwd()
os.listdir()
os.path.join()
os.listdir() returns bare file names without the directory, so you cannot open them as-is — join them with the directory via os.path.join(); the order is whatever the filesystem gives, so sort it yourself if you need it. New code usually reaches for pathlib for path manipulation and keeps os for processes, environment variables (os.environ) and operations like os.remove/os.rename.
Examples
import os, tempfile
print(os.getcwd()) # → ? текущая директория
tmp = tempfile.gettempdir() # кроссплатформенно: /tmp, C:\\Users\\...\\Temp
print(type(os.listdir(tmp))) # → <class 'list'>
# path.join — кроссплатформенное соединение путей
path = os.path.join(tmp, 'subdir', 'file.txt')
print(os.path.basename(path)) # → file.txt
# path.exists / isfile / isdir
print(os.path.exists(tmp)) # → True
print(os.path.isfile(tmp)) # → False
print(os.path.isdir(tmp)) # → True
# makedirs — каталог с родителями, exist_ok не ругается на существующий
work = os.path.join(tmp, 'test_os', 'sub')
os.makedirs(work, exist_ok=True)
print(os.path.isdir(work)) # → True
# environ — переменные окружения; набор у каждой ОС свой
print(type(os.environ.get('PATH', ''))) # → <class 'str'>
# os.walk — рекурсивный обход
for root, dirs, files in os.walk(os.path.join(tmp, 'test_os')):
print(os.path.basename(root)) # → ? имена каталогов обхода
See also
Open in the full glossarydocs.python.orgReport an inaccuracy