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

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

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

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

一、开篇

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

相关推荐

教你把多个视频合并成一个视频的方法

一.情况介绍当你有一个m3u8文件和一个目录,目录中有连续的视频片段,这些片段可以连成一段完整的视频。m3u8文件打开后像这样:m3u8文件,可以理解为播放列表,里面是播放视频片段的顺序。视频片段像这...

零代码编程:用kimichat合并一个文件夹下的多个文件

一个文件夹里面有很多个srt字幕文件,如何借助kimichat来自动批量合并呢?在kimichat对话框中输入提示词:你是一个Python编程专家,完成如下的编程任务:这个文件夹:D:\downloa...

Java APT_java APT 生成代码

JavaAPT(AnnotationProcessingTool)是一种在Java编译阶段处理注解的工具。APT会在编译阶段扫描源代码中的注解,并根据这些注解生成代码、资源文件或其他输出,...

Unit Runtime:一键运行 AI 生成的代码,或许将成为你的复制 + 粘贴神器

在我们构建了UnitMesh架构之后,以及对应的demo之后,便着手于实现UnitMesh架构。于是,我们就继续开始UnitRuntime,以用于直接运行AI生成的代码。PS:...

挣脱臃肿的枷锁:为什么说Vert.x是Java开发者手中的一柄利剑?

如果你是一名Java开发者,那么你的职业生涯几乎无法避开Spring。它如同一位德高望重的老国王,统治着企业级应用开发的大片疆土。SpringBoot的约定大于配置、SpringCloud的微服务...

五年后,谷歌还在全力以赴发展 Kotlin

作者|FredericLardinois译者|Sambodhi策划|Tina自2017年谷歌I/O全球开发者大会上,谷歌首次宣布将Kotlin(JetBrains开发的Ja...

kotlin和java开发哪个好,优缺点对比

Kotlin和Java都是常见的编程语言,它们有各自的优缺点。Kotlin的优点:简洁:Kotlin程序相对于Java程序更简洁,可以减少代码量。安全:Kotlin在类型系统和空值安全...

移动端架构模式全景解析:从MVC到MVVM,如何选择最佳设计方案?

掌握不同架构模式的精髓,是构建可维护、可测试且高效移动应用的关键。在移动应用开发中,选择合适的软件架构模式对项目的可维护性、可测试性和团队协作效率至关重要。随着应用复杂度的增加,一个良好的架构能够帮助...

颜值非常高的XShell替代工具Termora,不一样的使用体验!

Termora是一款面向开发者和运维人员的跨平台SSH终端与文件管理工具,支持Windows、macOS及Linux系统,通过一体化界面简化远程服务器管理流程。其核心定位是解决多平台环境下远程连接、文...

预处理的底层原理和预处理编译运行异常的解决方案

若文章对您有帮助,欢迎关注程序员小迷。助您在编程路上越走越好![Mac-10.7.1LionIntel-based]Q:预处理到底干了什么事情?A:预处理,顾名思义,预先做的处理。源代码中...

为“架构”再建个模:如何用代码描述软件架构?

在架构治理平台ArchGuard中,为了实现对架构的治理,我们需要代码+模型描述所要处理的内容和数据。所以,在ArchGuard中,我们有了代码的模型、依赖的模型、变更的模型等,剩下的两个...

深度解析:Google Gemma 3n —— 移动优先的轻量多模态大模型

2025年6月,Google正式发布了Gemma3n,这是一款能够在2GB内存环境下运行的轻量级多模态大模型。它延续了Gemma家族的开源基因,同时在架构设计上大幅优化,目标是让...

比分网开发技术栈与功能详解_比分网有哪些

一、核心功能模块一个基本的比分网通常包含以下模块:首页/总览实时比分看板:滚动展示所有正在进行的比赛,包含比分、比赛时间、红黄牌等关键信息。热门赛事/焦点战:突出显示重要的、关注度高的比赛。赛事导航...

设计模式之-生成器_一键生成设计

一、【概念定义】——“分步构建复杂对象,隐藏创建细节”生成器模式(BuilderPattern):一种“分步构建型”创建型设计模式,它将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建...

构建第一个 Kotlin Android 应用_kotlin简介

第一步:安装AndroidStudio(推荐IDE)AndroidStudio是官方推荐的Android开发集成开发环境(IDE),内置对Kotlin的完整支持。1.下载And...