Python3 OS

os 模块的目录操作、路径处理、环境变量与 os.path 常用方法。

Beginner
Key Points新代码优先用 pathlib;os.path 用 join 拼路径而不是手写斜杠;跨平台差异靠 os.sep 与 os.linesep 抹平。

os 模块的常用功能

os talks to the operating system: create and remove directories, list them, rename, and query the working directory. os.makedirs creates parents recursively and os.removedirs removes them.

Python
import os
import tempfile

root = tempfile.mkdtemp()
sub = os.path.join(root, 'a', 'b')
os.makedirs(sub)

print(os.path.isdir(sub))
print(sorted(os.listdir(root)))
print(os.getcwd() != '')

os.rename(os.path.join(root, 'a'), os.path.join(root, 'c'))
print(sorted(os.listdir(root)))
Output
True
['a']
True
['c']

路径操作

Never concatenate paths by hand — a literal / breaks on Windows. os.path.join picks the platform separator, os.path.split separates directory and name, splitext separates the extension.

Python
import os

p = os.path.join('data', 'sub', 'file.tar.gz')
print(p)
print(os.path.split(p))
print(os.path.splitext(p))
print(os.path.basename(p), os.path.dirname(p))
print(os.path.sep == os.sep)
Output
data\sub\file.tar.gz
('data\\sub', 'file.tar.gz')
('data\\sub\\file.tar', '.gz')
file.tar.gz data\sub
True
The backslashes above are the Windows separator; macOS / Linux print / instead. That is exactly why you should use os.path.join.

目录遍历

os.walk(top) traverses a tree top-down, yielding (dirpath, dirnames, filenames) per level. Filter by extension inside the loop to find files of a kind.

Python
import os
import tempfile

root = tempfile.mkdtemp()
os.makedirs(os.path.join(root, 'sub'))
for name in ('a.py', 'b.txt', os.path.join('sub', 'c.py')):
    open(os.path.join(root, name), 'w').close()

found = []
for dirpath, dirnames, filenames in os.walk(root):
    for fn in filenames:
        if fn.endswith('.py'):
            found.append(os.path.relpath(os.path.join(dirpath, fn), root))

print(sorted(found))
print(len(found))
Output
['a.py', 'sub\\c.py']
2

环境变量

os.environ is the environment mapping; os.environ.get(k, default) is the safe read, and os.getenv is equivalent. Changes affect only this process and its children, never the system.

Python
import os

print('PATH' in os.environ)
print(os.environ.get('NOT_SET_XYZ', 'fallback'))

os.environ['MY_VAR'] = '1'
print(os.getenv('MY_VAR'))

del os.environ['MY_VAR']
print(os.getenv('MY_VAR', 'gone'))
Output
True
fallback
1
gone

os.path 常用方法

exists tests presence, isfile/isdir test type, getsize returns bytes, abspath makes it absolute and normpath normalises. They have no side effects, so they are safe in conditions.

Python
import os
import tempfile

root = tempfile.mkdtemp()
p = os.path.join(root, 'x.txt')
with open(p, 'w', encoding='utf-8') as f:
    f.write('12345')

print(os.path.exists(p), os.path.isfile(p), os.path.isdir(p))
print(os.path.getsize(p))
print(os.path.isabs(p), os.path.isabs(os.path.abspath(p)))
print(os.path.normpath('a/./b/../c'))
Output
True True False
5
True True
a\c

Friends & Partners