百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

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

liuian 2025-06-30 17:57 57 浏览

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

一、开篇

本文将带你深入探索 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 模块创造更多可能!

相关推荐

驱动网卡(怎么从新驱动网卡)
驱动网卡(怎么从新驱动网卡)

网卡一般是指为电脑主机提供有线无线网络功能的适配器。而网卡驱动指的就是电脑连接识别这些网卡型号的桥梁。网卡只有打上了网卡驱动才能正常使用。并不是说所有的网卡一插到电脑上面就能进行数据传输了,他都需要里面芯片组的驱动文件才能支持他进行数据传输...

2026-01-30 00:37 liuian

win10更新助手装系统(微软win10更新助手)

1、点击首页“系统升级”的按钮,给出弹框,告诉用户需要上传IMEI码才能使用升级服务。同时给出同意和取消按钮。华为手机助手2、点击同意,则进入到“系统升级”功能华为手机助手华为手机助手3、在检测界面,...

windows11专业版密钥最新(windows11专业版激活码永久)

 Windows11专业版的正版密钥,我们是对windows的激活所必备的工具。该密钥我们可以通过微软商城或者通过计算机的硬件供应商去购买获得。获得了windows11专业版的正版密钥后,我...

手机删过的软件恢复(手机删除过的软件怎么恢复)
手机删过的软件恢复(手机删除过的软件怎么恢复)

操作步骤:1、首先,我们需要先打开手机。然后在许多图标中找到带有[文件管理]文本的图标,然后单击“文件管理”进入页面。2、进入页面后,我们将在顶部看到一行文本:手机,最新信息,文档,视频,图片,音乐,收藏,最后是我们正在寻找的[更多],单击...

2026-01-29 23:55 liuian

一键ghost手动备份系统步骤(一键ghost 备份)

  步骤1、首先把装有一键GHOST装系统的U盘插在电脑上,然后打开电脑马上按F2或DEL键入BIOS界面,然后就选择BOOT打USDHDD模式选择好,然后按F10键保存,电脑就会马上重启。  步骤...

怎么创建局域网(怎么创建局域网打游戏)

  1、购买路由器一台。进入路由器把dhcp功能打开  2、购买一台交换机。从路由器lan端口拉出一条网线查到交换机的任意一个端口上。  3、两台以上电脑。从交换机任意端口拉出网线插到电脑上(电脑设置...

精灵驱动器官方下载(精灵驱动手机版下载)

是的。驱动精灵是一款集驱动管理和硬件检测于一体的、专业级的驱动管理和维护工具。驱动精灵为用户提供驱动备份、恢复、安装、删除、在线更新等实用功能。1、全新驱动精灵2012引擎,大幅提升硬件和驱动辨识能力...

一键还原系统步骤(一键还原系统有哪些)

1、首先需要下载安装一下Windows一键还原程序,在安装程序窗口中,点击“下一步”,弹出“用户许可协议”窗口,选择“我同意该许可协议的条款”,并点击“下一步”。  2、在弹出的“准备安装”窗口中,可...

电脑加速器哪个好(电脑加速器哪款好)

我认为pp加速器最好用,飞速土豆太懒,急速酷六根本不工作。pp加速器什么网页都加速,太任劳任怨了!以上是个人观点,具体性能请自己试。ps:我家电脑性能很好。迅游加速盒子是可以加速电脑的。因为有过之...

任何u盘都可以做启动盘吗(u盘必须做成启动盘才能装系统吗)

是的,需要注意,U盘的大小要在4G以上,最好是8G以上,因为启动盘里面需要装系统,内存小的话,不能用来安装系统。内存卡或者U盘或者移动硬盘都可以用来做启动盘安装系统。普通的U盘就可以,不过最好U盘...

u盘怎么恢复文件(u盘文件恢复的方法)

开360安全卫士,点击上面的“功能大全”。点击文件恢复然后点击“数据”下的“文件恢复”功能。选择驱动接着选择需要恢复的驱动,选择接入的U盘。点击开始扫描选好就点击中间的“开始扫描”,开始扫描U盘数据。...

系统虚拟内存太低怎么办(系统虚拟内存占用过高什么原因)

1.检查系统虚拟内存使用情况,如果发现有大量的空闲内存,可以尝试释放一些不必要的进程,以释放内存空间。2.如果系统虚拟内存使用率较高,可以尝试增加系统虚拟内存的大小,以便更多的应用程序可以使用更多...

剪贴板权限设置方法(剪贴板访问权限)
剪贴板权限设置方法(剪贴板访问权限)

1、首先打开iphone手机,触碰并按住单词或图像直到显示选择选项。2、其次,然后选取“拷贝”或“剪贴板”。3、勾选需要的“权限”,最后选择开启,即可完成苹果剪贴板权限设置。仅参考1.打开苹果手机设置按钮,点击【通用】。2.点击【键盘】,再...

2026-01-29 21:37 liuian

平板系统重装大师(平板重装win系统)

如果你的平板开不了机,但可以连接上电脑,那就能好办,楼主下载安装个平板刷机王到你的个人电脑上,然后连接你的平板,平板刷机王会自动识别你的平板,平板刷机王上有你平板的我刷机包,楼主点击下载一个,下载完成...

联想官网售后服务网点(联想官网售后服务热线)

联想3c服务中心是联想旗下的官方售后,是基于互联网O2O模式开发的全新服务平台。可以为终端用户提供多品牌手机、电脑以及其他3C类产品的维修、保养和保险服务。根据客户需求层次,联想服务针对个人及家庭客户...