os — operating-system interface#
Part of a series demonstrating the 5 most-imported modules across the top PyPI packages (from imports_ranked.csv). Rank 3 of 5 — imported by 62.8% of crawled packages.
os and its os.path submodule handle files, directories, environment variables, and process info in a cross-platform way. All filesystem writes below happen inside a temporary directory that is cleaned up at the end.
Where am I? Process and system info#
import os
print('cwd :', os.getcwd())
print('os.name :', os.name)
print('pid :', os.getpid())
print('cpu_count:', os.cpu_count())
print('sep :', repr(os.sep), ' pathsep:', repr(os.pathsep))
cwd : /home/runner/work/py-apis/py-apis
os.name : posix
pid : 2341
cpu_count: 4
sep : '/' pathsep: ':'
Environment variables: environ, getenv#
import os
print('PATH has', len(os.environ.get('PATH', '').split(os.pathsep)), 'entries')
print('HOME :', os.getenv('HOME') or os.getenv('USERPROFILE'))
print('MISSING :', os.getenv('DEFINITELY_NOT_SET', '<default>'))
PATH has 18 entries
HOME : /home/runner
MISSING : <default>
os.path — manipulating paths as strings#
import os
p = os.path.join('data', 'raw', 'file.csv')
print('joined :', p)
print('dirname :', os.path.dirname(p))
print('basename:', os.path.basename(p))
print('splitext:', os.path.splitext(p))
print('exists? :', os.path.exists(p))
joined : data/raw/file.csv
dirname : data/raw
basename: file.csv
splitext: ('data/raw/file', '.csv')
exists? : False
Creating, listing, and walking directories#
We build a small tree inside a temp dir, then inspect it.
import os, tempfile
root = tempfile.mkdtemp(prefix='os_demo_')
os.makedirs(os.path.join(root, 'sub', 'deep'), exist_ok=True)
for i in range(3):
with open(os.path.join(root, f'f{i}.txt'), 'w') as fh:
fh.write('x' * (i + 1))
print('listdir:', sorted(os.listdir(root)))
print()
for dirpath, dirnames, filenames in os.walk(root):
rel = os.path.relpath(dirpath, root)
print(f'{rel:12} dirs={sorted(dirnames)} files={sorted(filenames)}')
listdir: ['f0.txt', 'f1.txt', 'f2.txt', 'sub']
. dirs=['sub'] files=['f0.txt', 'f1.txt', 'f2.txt']
sub dirs=['deep'] files=[]
sub/deep dirs=[] files=[]
os.stat — file metadata#
import os
target = os.path.join(root, 'f2.txt')
st = os.stat(target)
print('size :', st.st_size, 'bytes')
print('mode :', oct(st.st_mode))
print('mtime :', st.st_mtime)
size : 3 bytes
mode : 0o100644
mtime : 1786772925.880801
os.urandom — cryptographically strong random bytes#
import os
print(os.urandom(8).hex())
78f8ea389e37cbb2
Cleanup#
Remove the temp tree so nothing is left behind.
import shutil
shutil.rmtree(root, ignore_errors=True)
print('removed', root, '->', os.path.exists(root))
removed /tmp/os_demo_ncw5ob7z -> False