OS 库
官方文档: https://docs.python.org/zh-cn/3.12/library/os.html
os 是 Python 进行 文件操作、路径操作、进程管理、环境变量 的核心库之一。
import os
| 功能 | 方法 |
|---|---|
| 是否存在 | os.path.exists(path) |
| 是否文件 | os.path.isfile(path) |
| 是否目录 | os.path.isdir(path) |
os.path.join(a, b, c)
避免手写 /,跨平台最佳方法。
os.path.dirname(path) # 目录
os.path.basename(path) # 文件名
os.path.splitext(path) # ('a.txt', '.txt')
os.path.abspath(path)
os.path.realpath(path)
os.path.normpath(path)
open("file.txt", "w").close()
os.remove("file.txt")
os.rename("old.txt", "new.txt")
os.path.getsize("file.txt")
os.mkdir("folder") # 单层目录
os.makedirs("a/b/c", exist_ok=True) # 多层目录
os.rmdir("folder") # 必须空目录
os.removedirs("a/b/c") # 逐级删除空目录
os.listdir(".")
👑 文件扫描和递归遍历的最强方法
for root, dirs, files in os.walk("."):
print(root, dirs, files)
os.getenv("PATH")
os.environ["DEBUG"] = "1"
os.environ
os.getpid()
os.getppid()
os.system("ls -l")
⚠️ 不推荐执行复杂命令,建议使用 subprocess。
os._exit(0)
os.getcwd()
os.chdir("/path/to/dir")
os.chmod(path, 0o755)
os.chown(path, uid, gid)
os.stat(path)
os.urandom(16)
适合用于生成密钥、Token。
import os
for root, dirs, files in os.walk("."):
for name in files:
if name.endswith(".log"):
os.remove(os.path.join(root, name))
total = 0
for root, dirs, files in os.walk("."):
for f in files:
total += os.path.getsize(os.path.join(root, f))
print("Total size:", total)
DEBUG = os.getenv("DEBUG", "false").lower() == "true"
path = "data/output"
os.makedirs(path, exist_ok=True)
| 分类 | 功能 | 常用方法 |
|---|---|---|
| 路径处理 | 拼接 / 解析路径 | join basename dirname splitext |
| 文件操作 | 创建 / 删除 / 重命名 | remove rename |
| 目录操作 | 创建 / 删除 / 遍历 | mkdir makedirs listdir walk |
| 环境变量 | 获取 / 设置 | getenv environ |
| 工作目录 | 获取 / 切换 | getcwd chdir |
| 进程操作 | PID,执行命令 | getpid system |
| 权限 | chmod / chown | chmod chown |