史上最全!近万字梳理Python 开发必备的 os 模块(建议收藏)

点赞、收藏、加关注,下次找我不迷路

一、开篇

本文将带你深入探索 os 模块的核心功能,通过大量实际案例和代码示例,助你彻底掌握这个 Python 开发的必备神器。全文近万字,建议收藏后慢慢消化,用的时候拿出来查一查!


二、基础篇:从入门到精通的 10 个核心函数

2.1 获取当前工作目录:os.getcwd()

import os
current_dir = os.getcwd()

print(f"当前工作目录:{current_dir}")
  • 作用:返回当前 Python 脚本所在的工作目录。
  • 场景:当你需要读取或写入文件时,明确当前路径是关键。例如,在自动化脚本中,可能需要基于当前目录生成报告或日志。

2.2 切换工作目录:os.chdir(path)

os.chdir("/Users/yourname/project")  # 切换到指定目录
  • 注意:如果路径不存在,会抛出 FileNotFoundError。因此,建议先使用 os.path.exists(path) 检查路径是否存在。

2.3 列出目录内容:os.listdir(path)

files = os.listdir("/Users/yourname/project")
print(f"目录下的文件和文件夹:{files}")
  • 进阶用法:结合列表推导式过滤文件类型:
python_files = [f for f in os.listdir(".") if f.endswith(".py")]
print(f"Python 文件列表:{python_files}")

2.4 创建目录:os.mkdir(path) 和 os.makedirs(path)

os.mkdir("new_dir")  # 创建单层目录
os.makedirs("parent/child/grandchild") # 递归创建多层目录
  • 注意:若目录已存在,os.mkdir 会抛出 FileExistsError,而 os.makedirs 可通过 exist_ok=True 参数忽略错误:
os.makedirs("parent/child", exist_ok=True)

2.5 删除文件和目录:os.remove(path)、os.rmdir(path)、os.removedirs(path)

os.remove("test.txt")  # 删除文件
os.rmdir("empty_dir") # 删除空目录

os.removedirs("parent/child/grandchild") # 递归删除空目录
  • 警告:删除操作不可逆,请务必谨慎使用!建议先打印路径确认无误,再执行删除。

2.6 重命名文件或目录:os.rename(src, dst)

os.rename("old_file.txt", "new_file.txt")  # 重命名文件
os.rename("old_dir", "new_dir") # 重命名目录
  • 进阶技巧:结合 os.path 模块处理复杂路径:
src_path = os.path.join("data", "old.csv")
dst_path = os.path.join("data", "processed", "new.csv")

os.rename(src_path, dst_path)

2.7 路径操作:os.path 子模块

os.path 提供了一系列路径处理函数,堪称「路径管理神器」:

path = "/Users/yourname/project/file.txt"
print(os.path.abspath(path)) # 绝对路径

print(os.path.dirname(path)) # 目录部分

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

print(os.path.split(path)) # 拆分为目录和文件名

print(os.path.exists(path)) # 判断路径是否存在

print(os.path.isfile(path)) # 判断是否为文件

print(os.path.isdir(path)) # 判断是否为目录

print(os.path.getsize(path)) # 文件大小(字节)

print(os.path.join("dir1", "dir2", "file.txt")) # 路径拼接
  • 跨平台优势:os.path.join 会根据操作系统自动选择正确的路径分隔符,彻底告别 \ 和 / 的烦恼!

2.8 环境变量操作:os.environ

# 获取环境变量
print(os.environ.get("PATH"))

print(os.environ["HOME"])

# 设置环境变量(仅在当前进程有效)

os.environ["MY_VAR"] = "value"
  • 注意:修改 os.environ 不会影响系统环境变量,仅在当前 Python 进程中生效。

2.9 执行系统命令:os.system(command) 和 os.popen(command)

# 执行命令并返回状态码
os.system("ls -l")

# 执行命令并获取输出

output = os.popen("echo Hello World").read()

print(output)
  • 建议:对于复杂的命令执行,推荐使用 subprocess 模块,它提供了更灵活的控制和错误处理。

2.10 获取系统信息:os.name、os.uname()、os.getlogin()

print(os.name)  # 操作系统名称('nt' 或 'posix')
print(os.uname()) # 系统详细信息(仅限 Unix 系统)

print(os.getlogin()) # 当前登录用户名

三、进阶篇:10 个实用技巧让你效率翻倍

3.1 递归遍历目录:os.walk()

for root, dirs, files in os.walk("/Users/yourname/project"):
    print(f"当前目录:{root}")
    print(f"子目录:{dirs}")
    print(f"文件:{files}")
    print("-" * 50)


  • 场景:批量处理某个目录下的所有文件,例如统计代码行数、查找特定类型文件等。

3.2 创建临时文件和目录:tempfile 模块

import tempfile

# 创建临时文件
with tempfile.TemporaryFile(mode='w+') as f:
    f.write("临时数据")
    f.seek(0)
    print(f.read())

# 创建临时目录
with tempfile.TemporaryDirectory() as tmpdir:
    print(f"临时目录:{tmpdir}")
  • 优势:临时文件和目录会在使用完毕后自动删除,无需手动清理。

3.3 文件权限管理:os.chmod(path, mode)

os.chmod("file.txt", 0o755)  # 设置文件权限为 rwxr-xr-x
  • 权限说明:0o755 表示所有者可读、写、执行,组和其他用户可读、执行。

3.4 处理符号链接:os.path.realpath(path)

symlink_path = "/Users/yourname/project/link.txt"
real_path = os.path.realpath(symlink_path)
print(f"符号链接指向的真实路径:{real_path}")
  • 区别:os.path.abspath 仅解析相对路径,而 os.path.realpath 会解析符号链接。

3.5 批量重命名文件:结合正则表达式

import re

def rename_files(directory):
    for filename in os.listdir(directory):
        src = os.path.join(directory, filename)
        if not os.path.isfile(src):
            continue
        
        # 使用正则匹配旧文件名
        match = re.match(r"old_(\d+)\.txt", filename)
        if match:
            new_name = f"new_{match.group(1)}.txt"
            dst = os.path.join(directory, new_name)
            os.rename(src, dst)
            print(f"重命名:{filename} -> {new_name}")

rename_files("/Users/yourname/data")

3.6 获取文件的修改时间:os.path.getmtime(path)

import time

mtime = os.path.getmtime("file.txt")
print(f"文件最后修改时间:{time.ctime(mtime)}")

3.7 跨平台路径处理:pathlib 模块

from pathlib import Path

path = Path("data") / "file.txt"
print(path.resolve())  # 绝对路径
print(path.exists())  # 判断是否存在
print(path.parent)  # 父目录
  • 优势:pathlib 提供了面向对象的路径操作方式,代码更易读、更 Pythonic。

3.8 环境变量安全获取:os.getenv(key, default=None)

# 获取环境变量,不存在时返回默认值
api_key = os.getenv("API_KEY", "default_key")
print(f"API Key:{api_key}")

3.9 进程控制:os.getpid() 和 os.getppid()

print(f"当前进程 ID:{os.getpid()}")
print(f"父进程 ID:{os.getppid()}")

3.10 系统资源监控:结合 psutil 模块

import psutil

# 获取 CPU 使用率
print(f"CPU 使用率:{psutil.cpu_percent()}%")

# 获取内存使用情况
print(f"内存使用:{psutil.virtual_memory().percent}%")

# 获取磁盘空间
print(f"磁盘剩余空间:{psutil.disk_usage('/').free / (1024**3):.2f} GB")
  • 安装:pip install psutil

四、实战篇:5 个经典案例让你学以致用

4.1 自动化文件分类器

import os
import shutil

def organize_files(directory):
    # 创建分类目录
    categories = {
        "文档": [".doc", ".docx", ".pdf", ".txt"],
        "图片": [".jpg", ".jpeg", ".png", ".gif"],
        "视频": [".mp4", ".avi", ".mkv"],
        "压缩包": [".zip", ".rar", ".tar"],
    }

    for filename in os.listdir(directory):
        src = os.path.join(directory, filename)
        if not os.path.isfile(src):
            continue
        
        # 获取文件扩展名
        ext = os.path.splitext(filename)[1].lower()
        category = None

        # 判断文件类型
        for cat, exts in categories.items():
            if ext in exts:
                category = cat
                break

        if category:
            dest_dir = os.path.join(directory, category)
            os.makedirs(dest_dir, exist_ok=True)
            shutil.move(src, os.path.join(dest_dir, filename))
            print(f"移动文件:{filename} -> {category}")
        else:
            print(f"未知文件类型:{filename}")

organize_files("/Users/yourname/Downloads")

4.2 代码行数统计工具

import os

def count_lines(directory):
    total_lines = 0
    for root, dirs, files in os.walk(directory):
        for filename in files:
            if filename.endswith(".py"):
                file_path = os.path.join(root, filename)
                with open(file_path, "r", encoding="utf-8") as f:
                    lines = f.readlines()
                    total_lines += len(lines)
                    print(f"文件 {filename} 行数:{len(lines)}")
    print(f"总代码行数:{total_lines}")

count_lines("/Users/yourname/project")

4.3 系统监控脚本

import os
import time
import psutil

def monitor_system():
    while True:
        print("=" * 50)
        print(f"当前时间:{time.strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"CPU 使用率:{psutil.cpu_percent()}%")
        print(f"内存使用:{psutil.virtual_memory().percent}%")
        print(f"磁盘剩余空间:{psutil.disk_usage('/').free / (1024**3):.2f} GB")
        print(f"当前进程数:{len(psutil.pids())}")
        print("=" * 50)
        time.sleep(60)  # 每 60 秒更新一次

monitor_system()

4.4 跨平台文件同步工具

import os
import shutil

def sync_files(src_dir, dst_dir):
    # 确保目标目录存在
    os.makedirs(dst_dir, exist_ok=True)

    # 遍历源目录
    for root, dirs, files in os.walk(src_dir):
        # 计算目标路径
        relative_path = os.path.relpath(root, src_dir)
        dst_root = os.path.join(dst_dir, relative_path)
        os.makedirs(dst_root, exist_ok=True)

        # 同步文件
        for filename in files:
            src_file = os.path.join(root, filename)
            dst_file = os.path.join(dst_root, filename)
            # 仅当文件存在或修改时复制
            if not os.path.exists(dst_file) or os.path.getmtime(src_file) > os.path.getmtime(dst_file):
                shutil.copy2(src_file, dst_file)
                print(f"复制文件:{src_file} -> {dst_file}")

    # 删除目标目录中多余的文件
    for root, dirs, files in os.walk(dst_dir, topdown=False):
        for filename in files:
            dst_file = os.path.join(root, filename)
            src_file = os.path.join(src_dir, os.path.relpath(dst_file, dst_dir))
            if not os.path.exists(src_file):
                os.remove(dst_file)
                print(f"删除多余文件:{dst_file}")
        for dirname in dirs:
            dst_dir_path = os.path.join(root, dirname)
            if not os.listdir(dst_dir_path):
                os.rmdir(dst_dir_path)
                print(f"删除空目录:{dst_dir_path}")

sync_files("/Users/yourname/source", "/Users/yourname/destination")

4.5 自动化备份脚本

import os
import shutil
import time

def backup_files(source_dir, backup_dir):
    # 创建备份目录
    timestamp = time.strftime("%Y%m%d%H%M%S")
    backup_path = os.path.join(backup_dir, f"backup_{timestamp}")
    os.makedirs(backup_path, exist_ok=True)

    # 复制文件
    for root, dirs, files in os.walk(source_dir):
        relative_path = os.path.relpath(root, source_dir)
        backup_root = os.path.join(backup_path, relative_path)
        os.makedirs(backup_root, exist_ok=True)
        for filename in files:
            src_file = os.path.join(root, filename)
            dst_file = os.path.join(backup_root, filename)
            shutil.copy2(src_file, dst_file)
            print(f"备份文件:{src_file} -> {dst_file}")

    print(f"备份完成,路径:{backup_path}")

backup_files("/Users/yourname/project", "/Users/yourname/backups")

五、避坑指南:10 个常见错误及解决方案

5.1 路径分隔符错误

错误

file_path = "C:\new_folder\file.txt"  # 在 Windows 中会报错

解决方案

  • 使用原始字符串:
file_path = r"C:\new_folder\file.txt"
  • 使用 os.path.join:
file_path = os.path.join("C:", "new_folder", "file.txt")

5.2 删除非空目录

错误

os.rmdir("non_empty_dir")  # 会抛出 OSError

解决方案

  • 使用 shutil.rmtree 删除非空目录:
import shutil

shutil.rmtree("non_empty_dir")

5.3 权限不足

错误

os.remove("/root/secret.txt")  # 普通用户无权限

解决方案

  • 以管理员身份运行脚本。
  • 修改文件权限:
os.chmod("/root/secret.txt", 0o777)

5.4 环境变量不存在

错误

api_key = os.environ["API_KEY"]  # 若环境变量未设置,会抛出 KeyError

解决方案

  • 使用 get 方法并提供默认值:
api_key = os.environ.get("API_KEY", "default_key")

5.5 路径拼接错误

错误

dir_path = "/home/user"
file_name = "file.txt"

file_path = dir_path + "/" + file_name # 跨平台时可能出错

解决方案

  • 使用 os.path.join:
file_path = os.path.join(dir_path, file_name)

5.6 文件或目录不存在

错误

os.remove("nonexistent_file.txt")  # 会抛出 FileNotFoundError

解决方案

  • 先检查路径是否存在:
if os.path.exists("nonexistent_file.txt"):
    os.remove("nonexistent_file.txt")


5.7 执行危险命令

错误

command = input("请输入系统命令:")
os.system(command) # 存在安全风险

解决方案

  • 避免直接执行用户输入的命令,或使用 subprocess 模块进行更严格的控制。

5.8 符号链接导致的问题

错误

symlink_path = "/path/to/link"
real_path = os.path.abspath(symlink_path) # 未解析符号链接

解决方案

  • 使用 os.path.realpath 解析符号链接:
real_path = os.path.realpath(symlink_path)

5.9 临时文件未自动删除

错误

temp_file = tempfile.TemporaryFile()
temp_file.write(b"test")
# 未关闭文件,可能导致文件未被删除

解决方案

  • 使用 with 语句自动管理资源:
with tempfile.TemporaryFile() as f:
    f.write(b"test")


5.10 跨平台代码兼容性问题

错误

if os.name == "nt":
    command = "dir"
else:
    command = "ls"
os.system(command)  # 仅适用于简单命令


解决方案

  • 使用 subprocess 模块或 shutil 模块的跨平台函数。

六、面试必备:10 个高频问题及答案

6.1 请解释 os.path.abspath 和 os.path.realpath 的区别

  • os.path.abspath:将相对路径转换为绝对路径,不解析符号链接。
  • os.path.realpath:解析符号链接,返回文件的真实路径。

6.2 如何递归遍历目录下的所有文件?

使用 os.walk 函数:

for root, dirs, files in os.walk("/path/to/directory"):
    for file in files:
        print(os.path.join(root, file))


6.3 如何获取文件的大小?

使用 os.path.getsize:

size = os.path.getsize("file.txt")

6.4 如何判断一个路径是文件还是目录?

使用 os.path.isfile 和 os.path.isdir:

if os.path.isfile("path"):
    print("是文件")
elif os.path.isdir("path"):
    print("是目录")


6.5 如何执行系统命令并获取输出?

使用 os.popen 或 subprocess 模块:

output = os.popen("echo Hello").read()

6.6 如何修改文件的权限?

使用 os.chmod:

os.chmod("file.txt", 0o755)

6.7 如何处理跨平台路径分隔符?

使用 os.path.join 或 pathlib 模块。

6.8 如何创建临时文件和目录?

使用 tempfile 模块:

import tempfile

with tempfile.TemporaryFile() as f:
    pass

with tempfile.TemporaryDirectory() as tmpdir:
    pass

6.9 如何获取当前进程的 ID?

使用 os.getpid()。

6.10 如何处理环境变量?

使用 os.environ 获取和设置环境变量:

# 获取
print(os.environ.get("PATH"))

# 设置
os.environ["MY_VAR"] = "value"

最后,不要忘记将本文收藏起来,随时查阅!如果你觉得本文对你有帮助,欢迎分享给更多的 Python 开发者。让我们一起在 Python 的世界里,用 os 模块创造更多可能!

原文链接:,转发请注明来源!