当前位置:首页>python>Python os 模块 超详细精讲

Python os 模块 超详细精讲

  • 2026-10-11 08:08:50
Python os 模块 超详细精讲

一、os 模块是什么

os 模块是 Python 用来和操作系统交互的标准库,主要用于:

  • • 文件/目录创建、删除、重命名、遍历
  • • 路径处理(拼接、获取绝对路径、扩展名)
  • • 获取系统环境变量
  • • 获取当前路径、切换目录
  • • 查看文件大小、判断文件是否存在

二、🔥 最常用:路径操作(重点)

1. 获取当前工作目录

import os

# 当前程序运行目录
print(os.getcwd())

2. 绝对路径 / 相对路径

# 转绝对路径
print(os.path.abspath("test.txt"))

3. 路径拼接(最常用,跨平台不乱码)

path = os.path.join("folder", "sub", "test.txt")
print(path)

✅ 一定要用 os.path.join,不要手动拼字符串

4. 获取路径中的文件名/目录名/后缀

path = "a/b/c/test.txt"

# 文件名
print(os.path.basename(path))  # test.txt

# 目录部分
print(os.path.dirname(path))   # a/b/c

# 拆分文件名和后缀
print(os.path.splitext("test.txt"))  # ('test', '.txt')

5. 判断文件/目录是否存在

# 判断是否存在
print(os.path.exists("test.txt"))

# 判断是不是文件
print(os.path.isfile("test.txt"))

# 判断是不是文件夹
print(os.path.isdir("test_dir"))

三、🔥 目录操作(增删改查)

1. 创建目录

# 创建单层文件夹
os.mkdir("test")

# 递归创建多层文件夹
os.makedirs("a/b/c")

2. 删除目录/文件

# 删除文件
os.remove("test.txt")

# 删除空目录
os.rmdir("test")

# 递归删除多层空目录
os.removedirs("a/b/c")

3. 重命名

os.rename("old.txt", "new.txt")

4. 遍历目录(列出所有文件)

# 列出当前目录下所有文件/文件夹
print(os.listdir("."))

5. 深度遍历目录(os.walk)

for root, dirs, files in os.walk("."):
print("当前路径:", root)
print("文件夹:", dirs)
print("文件:", files)

四、🔥 环境变量操作

1. 获取所有环境变量

env = os.environ
print(env)

2. 获取某个环境变量(推荐)

# 安全获取,不存在返回 None
print(os.getenv("PATH"))
print(os.getenv("HOME"))
print(os.getenv("USERNAME"))

3. 设置环境变量(当前程序有效)

os.environ["MY_VAR"] = "hello"

五、🔥 进程相关(了解)

1. 运行系统命令

os.system("dir")   # Windows
os.system("ls")    # Mac/Linux

2. 获取进程 ID

print(os.getpid())  # 当前进程ID
print(os.getppid()) # 父进程ID

3. 退出程序

os.exit()

六、🔥 os.path 高频方法速查表

方法
作用
os.path.abspath(path)
转绝对路径
os.path.join(a, b, c)
安全拼接路径
os.path.exists(path)
是否存在
os.path.isfile(path)
是否是文件
os.path.isdir(path)
是否是文件夹
os.path.basename(path)
取文件名
os.path.dirname(path)
取目录
os.path.splitext(path)
分离文件名与后缀

七、🔥 超级实用小例子

遍历文件夹,找出所有 .txt 文件

import os

for f in os.listdir("."):
if os.path.splitext(f)[1] == ".txt":
print(f)

📝 总结

  • • os 模块 = 操作系统交互工具
  • • os.path = 路径处理工具
  • • 工作中 90% 用:
    • • os.path.join
    • • os.path.exists
    • • os.listdir
    • • os.walk
    • • os.getcwd()
    • • os.getenv()

最新文章

随机文章