史上最全!近万字梳理Python 开发必备的 os 模块(建议收藏)
liuian 2025-06-30 17:57 34 浏览
点赞、收藏、加关注,下次找我不迷路
一、开篇
本文将带你深入探索 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:
pass6.9 如何获取当前进程的 ID?
使用 os.getpid()。
6.10 如何处理环境变量?
使用 os.environ 获取和设置环境变量:
# 获取
print(os.environ.get("PATH"))
# 设置
os.environ["MY_VAR"] = "value"最后,不要忘记将本文收藏起来,随时查阅!如果你觉得本文对你有帮助,欢迎分享给更多的 Python 开发者。让我们一起在 Python 的世界里,用 os 模块创造更多可能!
相关推荐
- 搭建一个20人的办公网络(适用于20多人的小型办公网络环境)
-
楼主有5台机上网,则需要一个8口路由器,组网方法如下:设备:1、8口路由器一台,其中8口为LAN(局域网)端口,一个WAN(广域网)端口,价格100--400元2、网线N米,这个你自己会看了:)...
- 笔记本电脑各种参数介绍(笔记本电脑各项参数新手普及知识)
-
1、CPU:这个主要取决于频率和二级缓存,频率越高、二级缓存越大,速度越快,现在的CPU有三级缓存、四级缓存等,都影响相应速度。2、内存:内存的存取速度取决于接口、颗粒数量多少与储存大小,一般来说,内...
- 汉字上面带拼音输入法下载(字上面带拼音的输入法是哪个)
-
使用手机上的拼音输入法打成汉字的方法如下:1.打开手机上的拼音输入法,在输入框中输入汉字的拼音,例如“nihao”。2.根据输入法提示的候选词,选择正确的汉字。例如,如果输入“nihao”,输...
- xpsp3安装版系统下载(windowsxpsp3安装教程)
-
xpsp3纯净版在采用微软封装部署技术的基础上,结合作者的实际工作经验,融合了许多实用的功能。它通过一键分区、一键装系统、自动装驱动、一键设定分辨率,一键填IP,一键Ghost备份(恢复)等一系列...
- 没有备份的手机数据怎么恢复
-
手机没有备份恢复数据方法如下1、使用数据线将手机与电脑连接好,在“我的电脑”中可以看到手机的盘符。 2、将手机开启USB调试模式。在手机设置中找到开发者选项,然后点击“开启USB调试模式”。 3、...
- 电脑怎么激活windows11专业版
-
win11专业版激活方法有多种,以下提供两种常用的激活方式:方法一:使用激活密钥激活。在win11桌面上右键点击“此电脑”,选择“属性”选项。进入属性页面后,点击“更改产品密钥或升级windows”。...
- 华为手机助手下载官网(华为手机助手app下载专区)
-
华为手机助手策略调整,已不支持从应用市场下载手机助手,目前华为手机助手是需要在电脑上下载或更新手机助手到最新版本,https://consumer.huawei.com/cn/support/his...
- 光纤线断了怎么接(宽带光纤线断了怎么接)
-
宽带光纤线断了可以重接,具体操作方法如下:1、光纤连接的时候要根据束管内,同色相连,同芯相连,按顺序进行连接,由大到小。一般有三种连接方法,分别是熔接、活动连接和机械连接。2、连接的时候要开剥光缆,抛...
- win7旗舰版和专业版区别(win7旗舰版跟专业版)
-
1、功能区别:Win7旗舰版比专业版多了三个功能,分别是Bitlocker、BitlockerToGo和多语言界面; 2、用途区别:旗舰版的功能是所有版本中最全最强大的,占用的系统资源,...
- 万能连接钥匙(万能wifi连接钥匙下载)
-
1、首先打开wifi万能钥匙软件,若手机没有开启WLAN,就根据软件提示打开WLAN开关;2、打开WLAN开关后,会显示附近的WiFi,如果知道密码,可点击相应WiFi后点击‘输入密码’连接;3、若不...
- 雨林木风音乐叫什么(雨林木风是啥)
-
雨林木风的创始人是陈年鑫先生。陈年鑫先生于1999年创立了雨林木风公司,其初衷是为满足中国市场对高品质、高性能电脑的需求。在陈年鑫先生的领导下,雨林木风以技术创新、产品质量和客户服务为核心价值,不断推...
- aics6序列号永久序列号(aics6破解序列号)
-
关于AICS6这个版本,虽然是比较久远的版本,但是在功能上也是十分全面和强大的,作为一名平面设计师的话,AICS6的现有的功能已经能够应付几乎所有的设计工作了……到底AICC2019的功能是不是...
- 手机可以装电脑系统吗(手机可以装电脑系统吗怎么装)
-
答题公式1:手机可以通过数据线或无线连接的方式给电脑装系统。手机安装系统需要一定的技巧和软件支持,一般需要通过数据线或无线连接的方式与电脑连接,并下载相应的软件和系统文件进行安装。对于大部分手机用户来...
- 一周热门
- 最近发表
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)
- c++ 字符串查找 (35)
- mysql刷新权限 (34)
