os模块
os 模块提供了与操作系统交互的接口,涵盖文件目录操作、进程管理、环境变量访问等功能。它是 Python 脚本与底层系统沟通的桥梁,几乎所有涉及文件系统或系统调用的程序都会用到它。
文件与目录操作
路径拼接:os.path.join 自动处理不同系统的路径分隔符
import os
path = os.path.join("home", "user", "documents", "file.txt")
print path # Linux: home/user/documents/file.txt
# Windows: home\user\documents\file.txt
Windows 使用反斜杠 \,Linux/macOS 使用正斜杠 /。os.path.join 根据当前系统选择正确的分隔符,保证代码跨平台。
获取绝对路径:
print os.path.abspath(".") # 当前目录的绝对路径
print os.path.abspath("../") # 上级目录的绝对路径
路径分解:
path = "/home/user/documents/file.txt"
print os.path.dirname(path) # /home/user/documents
print os.path.basename(path) # file.txt
print os.path.split(path) # ('/home/user/documents', 'file.txt')
print os.path.splitext(path) # ('/home/user/documents/file', '.txt')
检查路径属性:
print os.path.exists("/tmp") # True/False
print os.path.isfile("/tmp") # 是否是文件
print os.path.isdir("/tmp") # 是否是目录
print os.path.isabs("/tmp") # 是否是绝对路径
目录操作:
os.mkdir("new_dir") # 创建单级目录
os.makedirs("a/b/c") # 递归创建多级目录
os.rmdir("new_dir") # 删除空目录
os.removedirs("a/b/c") # 递归删除空目录
os.listdir(".") # 列出目录内容
文件操作:
os.remove("file.txt") # 删除文件
os.rename("old.txt", "new.txt") # 重命名
os.stat("file.txt") # 文件元信息(大小、修改时间等)
环境变量
print os.environ["HOME"] # 获取环境变量
print os.environ.get("PATH") # 安全获取(不存在返回 None)
os.environ["MY_VAR"] = "value" # 设置环境变量
print os.environ["MY_VAR"] # value
环境变量的修改只在当前进程有效,不会影响父进程或系统环境。
进程信息
print os.getpid() # 当前进程 ID
print os.getcwd() # 当前工作目录
os.chdir("/tmp") # 切换工作目录
执行系统命令(旧方式)
os.system 执行 shell 命令并返回退出码:
result = os.system("ls -la")
print result # 0 表示成功,非 0 表示失败
os.popen 执行命令并获取输出:
output = os.popen("ls -la").read()
print output
注意:Python 2.7 中 os.system 和 os.popen 已被 subprocess 模块取代,后者更安全、功能更强大。详见 subprocess 章节。
路径遍历
# 遍历目录树
for root, dirs, files in os.walk("/tmp"):
print "Directory:", root
for file in files:
print " File:", os.path.join(root, file)
os.walk 递归遍历目录,每次迭代返回 (当前目录, 子目录列表, 文件列表)。
实际应用
批量重命名:
import os
def batch_rename(directory, old_ext, new_ext):
for filename in os.listdir(directory):
if filename.endswith(old_ext):
old_path = os.path.join(directory, filename)
new_path = os.path.join(
directory,
filename[:-len(old_ext)] + new_ext
)
os.rename(old_path, new_path)
print "Renamed:", filename
batch_rename(".", ".txt", ".md")
查找大文件:
def find_large_files(directory, min_size):
for root, dirs, files in os.walk(directory):
for file in files:
path = os.path.join(root, file)
size = os.path.getsize(path)
if size > min_size:
print "%s: %d bytes" % (path, size)
find_large_files("/var/log", 1024 * 1024) # 找大于 1MB 的文件
创建临时目录:
import tempfile
tmpdir = tempfile.mkdtemp(prefix="myapp_")
print tmpdir # /tmp/myapp_XXXXXX
# 使用完后清理
import shutil
shutil.rmtree(tmpdir)
os.path 的替代方案
Python 3.4+ 引入了 pathlib 模块,用面向对象的方式处理路径。Python 2.7 没有 pathlib,但可以通过 pip install pathlib 安装第三方版本,或者继续使用 os.path。
# Python 2.7 的 os.path 方式
path = os.path.join(os.path.dirname(__file__), "data", "config.json")
# Python 3 的 pathlib 方式(供参考)
# from pathlib import Path
# path = Path(__file__).parent / "data" / "config.json"