当前位置: 首页 > news >正文

【Python自动化】 22 Python os 库详解

os 模块是 Python 中最重要和常用的标准库之一,提供了与操作系统交互的各种功能。

一、导入 os 模块

import os

二、文件和目录操作

1 路径操作
# 获取当前工作目录(Get Current Working Directory)
current_dir = os.getcwd()
print(f"当前目录: {current_dir}")# 改变当前工作目录(Change Directory)
os.chdir('/path/to/directory')# 获取绝对路径
abs_path = os.path.abspath('relative/path')# 路径拼接(推荐使用)
full_path = os.path.join('dir1', 'dir2', 'file.txt')
# 输出: dir1/dir2/file.txt (Linux) 或 dir1\dir2\file.txt (Windows)# 路径分割
dirname, filename = os.path.split('/path/to/file.txt')
# dirname = '/path/to', filename = 'file.txt'# 文件名和扩展名分割
name, ext = os.path.splitext('file.txt')
# name = 'file', ext = '.txt'# 获取路径的目录部分
directory = os.path.dirname('/path/to/file.txt')
# directory = '/path/to'# 获取路径的文件名部分
filename = os.path.basename('/path/to/file.txt')
# filename = 'file.txt'
2 文件和目录检测
# 检查路径是否存在
exists = os.path.exists('/path/to/file')# 检查是否是文件
is_file = os.path.isfile('/path/to/file.txt')# 检查是否是目录
is_dir = os.path.isdir('/path/to/directory')# 检查是否是链接
is_link = os.path.islink('/path/to/link')# 检查路径是否是绝对路径
is_abs = os.path.isabs('/path/to/file')# 获取文件大小(字节)
size = os.path.getsize('/path/to/file.txt')# 获取文件最后修改时间(时间戳)
mtime = os.path.getmtime('/path/to/file.txt')# 获取文件创建时间(时间戳)
ctime = os.path.getctime('/path/to/file.txt')# 获取文件最后访问时间(时间戳)
atime = os.path.getatime('/path/to/file.txt')
3 文件和目录管理
# 创建目录
os.mkdir('new_directory')  # 创建单级目录
os.makedirs('path/to/nested/directory', exist_ok=True)  # 创建多级目录# 删除文件
os.remove('file.txt')# 删除空目录
os.rmdir('empty_directory')# 删除目录树(包括所有内容)
import shutil
shutil.rmtree('directory_with_content')# 重命名/移动文件或目录
os.rename('old_name.txt', 'new_name.txt')
os.rename('old_dir', 'new_dir')# 复制文件(需要 shutil)
import shutil
shutil.copy2('source.txt', 'destination.txt')  # 保留元数据# 获取目录内容列表
files = os.listdir('.')  # 当前目录所有文件和目录# 递归遍历目录(推荐使用)
for root, dirs, files in os.walk('/path/to/directory'):print(f"当前目录: {root}")print(f"子目录: {dirs}")print(f"文件: {files}")

三、环境变量和系统信息

1 环境变量操作
# 获取环境变量
home_dir = os.environ.get('HOME')  # Unix/Linux
home_dir = os.environ.get('USERPROFILE')  # Windows# 获取所有环境变量
for key, value in os.environ.items():print(f"{key}: {value}")# 设置环境变量(当前进程)
os.environ['MY_VAR'] = 'my_value'# 检查环境变量是否存在
if 'PATH' in os.environ:print("PATH 环境变量存在")# 获取 PATH 环境变量
path_dirs = os.environ.get('PATH', '').split(os.pathsep)
2 系统信息
# 获取操作系统名称
os_name = os.name
# 'posix' (Unix/Linux/Mac), 'nt' (Windows), 'java' (Jython)# 获取平台详细信息
import platform
print(platform.system())  # 'Windows', 'Linux', 'Darwin'
print(platform.release())  # 系统版本号# 获取文件系统的分隔符
sep = os.sep  # '/' 或 '\'
path_sep = os.pathsep  # ':' 或 ';'# 获取行分隔符
line_sep = os.linesep  # '\n' 或 '\r\n'

四、进程管理

1 执行系统命令
# 执行系统命令并获取返回值
exit_code = os.system('ls -l')  # 返回退出状态码# 执行命令并获取输出(推荐使用 subprocess)
import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)# 获取当前进程ID
pid = os.getpid()
print(f"当前进程ID: {pid}")# 获取父进程ID
ppid = os.getppid()
print(f"父进程ID: {ppid}")
2 进程控制
# 退出程序
os._exit(0)  # 立即退出,不执行清理操作# 创建子进程(Unix/Linux)
pid = os.fork()
if pid == 0:# 子进程print("这是子进程")os._exit(0)
else:# 父进程print(f"这是父进程,子进程ID: {pid}")

五、文件权限和属性

1 权限管理
# 改变文件权限(Unix/Linux)
os.chmod('file.txt', 0o755)  # rwxr-xr-x# 获取文件权限
stat_info = os.stat('file.txt')
permissions = stat_info.st_mode & 0o777# 改变文件所有者(需要权限)
os.chown('file.txt', uid, gid)  # Unix/Linux# 获取文件状态信息
stat_info = os.stat('file.txt')
print(f"大小: {stat_info.st_size} 字节")
print(f"最后修改时间: {stat_info.st_mtime}")
print(f"最后访问时间: {stat_info.st_atime}")

六、路径遍历和文件搜索

1 高级文件遍历
# 使用 os.walk() 递归遍历
for root, dirs, files in os.walk('/path/to/directory'):# 过滤隐藏文件和目录dirs[:] = [d for d in dirs if not d.startswith('.')]files = [f for f in files if not f.startswith('.')]for file in files:full_path = os.path.join(root, file)print(full_path)# 使用 os.scandir()(更高效)
with os.scandir('/path/to/directory') as entries:for entry in entries:if entry.is_file():print(f"文件: {entry.name}, 大小: {entry.stat().st_size}")elif entry.is_dir():print(f"目录: {entry.name}")
2 文件搜索功能
def find_files(directory, pattern=None, file_type='both'):"""查找指定目录下的文件Args:directory: 要搜索的目录pattern: 文件名模式(可选)file_type: 'file', 'dir', 或 'both'"""results = []for root, dirs, files in os.walk(directory):if file_type in ['file', 'both']:for file in files:if pattern is None or pattern in file:results.append(os.path.join(root, file))if file_type in ['dir', 'both']:for dir_name in dirs:if pattern is None or pattern in dir_name:results.append(os.path.join(root, dir_name))return results# 使用示例
pdf_files = find_files('/path/to/docs', '.pdf', 'file')
print(f"找到 {len(pdf_files)} 个PDF文件")

七、实用工具函数

1 路径处理工具
def normalize_path(path):"""规范化路径,处理 .. 和 ."""return os.path.normpath(path)def ensure_directory_exists(path):"""确保目录存在,不存在则创建"""os.makedirs(path, exist_ok=True)def get_file_info(file_path):"""获取文件的详细信息"""if not os.path.exists(file_path):return Nonestat_info = os.stat(file_path)return {'path': file_path,'size': stat_info.st_size,'modified': stat_info.st_mtime,'created': stat_info.st_ctime,'is_file': os.path.isfile(file_path),'is_dir': os.path.isdir(file_path)}
2 批量文件操作
def batch_rename_files(directory, pattern, replacement):"""批量重命名文件"""renamed_count = 0for filename in os.listdir(directory):if pattern in filename:new_name = filename.replace(pattern, replacement)old_path = os.path.join(directory, filename)new_path = os.path.join(directory, new_name)os.rename(old_path, new_path)renamed_count += 1print(f"重命名: {filename} -> {new_name}")return renamed_countdef find_large_files(directory, size_limit_mb=100):"""查找大于指定大小的文件"""large_files = []size_limit = size_limit_mb * 1024 * 1024for root, dirs, files in os.walk(directory):for file in files:file_path = os.path.join(root, file)try:size = os.path.getsize(file_path)if size > size_limit:large_files.append((file_path, size))except OSError:continuereturn sorted(large_files, key=lambda x: x[1], reverse=True)

八、错误处理和最佳实践

1 错误处理
import os
import errnodef safe_file_operation(func, *args, **kwargs):"""安全的文件操作包装器"""try:return func(*args, **kwargs)except OSError as e:if e.errno == errno.ENOENT:print("文件或目录不存在")elif e.errno == errno.EACCES:print("权限不足")elif e.errno == errno.ENOSPC:print("磁盘空间不足")else:print(f"操作系统错误: {e}")return None# 使用示例
result = safe_file_operation(os.remove, 'nonexistent.txt')
2 最佳实践
# 1. 总是使用 os.path.join() 而不是字符串拼接
# 错误的方式
path = 'dir1' + '/' + 'dir2' + '/' + 'file.txt'# 正确的方式
path = os.path.join('dir1', 'dir2', 'file.txt')# 2. 检查文件是否存在后再操作
if os.path.exists('file.txt'):with open('file.txt', 'r') as f:content = f.read()
else:print("文件不存在")# 3. 使用 with 语句处理文件
with open('file.txt', 'r') as f:content = f.read()# 4. 处理不同操作系统的路径差异
if os.name == 'nt':  # Windows# Windows 特定的处理pass
else:  # Unix/Linux# Unix 特定的处理pass

九、综合示例

import os
import datetimedef analyze_directory(directory):"""分析目录结构"""if not os.path.exists(directory):print("目录不存在")returntotal_files = 0total_size = 0file_types = {}for root, dirs, files in os.walk(directory):# 跳过隐藏目录dirs[:] = [d for d in dirs if not d.startswith('.')]for file in files:# 跳过隐藏文件if file.startswith('.'):continuefile_path = os.path.join(root, file)try:size = os.path.getsize(file_path)total_size += sizetotal_files += 1# 统计文件类型_, ext = os.path.splitext(file)ext = ext.lower() if ext else '无扩展名'file_types[ext] = file_types.get(ext, 0) + 1except OSError:continue# 输出结果print(f"目录: {directory}")print(f"总文件数: {total_files}")print(f"总大小: {total_size / (1024*1024):.2f} MB")print("\n文件类型分布:")for ext, count in sorted(file_types.items(), key=lambda x: x[1], reverse=True):print(f"  {ext}: {count} 个文件")# 使用示例
analyze_directory('/path/to/analyze')

十、总结

os 模块是 Python 中处理文件和目录操作的核心库,提供了:

  • 路径操作:路径拼接、分割、规范化
  • 文件检测:存在性检查、类型判断、属性获取
  • 目录管理:创建、删除、遍历目录
  • 环境变量:获取和设置环境变量
  • 系统信息:获取操作系统相关信息
  • 进程管理:执行命令、获取进程信息

掌握 os 模块的使用对于进行文件操作、系统编程和自动化脚本编写至关重要。


文章转载自:

http://iCWlzCWe.hpjpy.cn
http://iQ6aTj44.hpjpy.cn
http://rDxluhcU.hpjpy.cn
http://edpRs7k9.hpjpy.cn
http://lO9dAfFB.hpjpy.cn
http://YjWDaARt.hpjpy.cn
http://7Vwkyrd8.hpjpy.cn
http://Vs0aI48l.hpjpy.cn
http://Quadtgtq.hpjpy.cn
http://o26jX56D.hpjpy.cn
http://33zWvp1z.hpjpy.cn
http://ntiJ0KNV.hpjpy.cn
http://bE2nUOg8.hpjpy.cn
http://F048sxut.hpjpy.cn
http://KfTKTbbY.hpjpy.cn
http://i5dCQBGo.hpjpy.cn
http://LxDF2n1n.hpjpy.cn
http://s7zny4gI.hpjpy.cn
http://KZhw6qt4.hpjpy.cn
http://ASHsTv4Q.hpjpy.cn
http://wq8PdWtC.hpjpy.cn
http://piKLd9vY.hpjpy.cn
http://qz7j8uyn.hpjpy.cn
http://BNiOg7Ux.hpjpy.cn
http://wKSbxTd4.hpjpy.cn
http://RAAw631s.hpjpy.cn
http://CwmCmhrs.hpjpy.cn
http://YJ5zrPw2.hpjpy.cn
http://tuVsuJ8t.hpjpy.cn
http://2G90p7Lx.hpjpy.cn
http://www.dtcms.com/a/378698.html

相关文章:

  • 智能投影仪技术解析:从显示工具到智慧影音终端的演进
  • 下一代社媒运营工具:亚矩阵云手机集成AIGC与数字人技术引领内容革命
  • 在Excel中删除大量间隔空白行
  • Android Studio Meerkat | 2024.3.1 Gradle Tasks不展示
  • 新版Android Studio能打包但无法run ‘app‘,编译通过后手机中没有安装,顶部一直转圈
  • CSS 伪类选择器
  • 2年1170万!39岁的霍福德,还有多少油?
  • IsaacSim Segmentation
  • CLIP、DALL·E 1的解读
  • Go 语言开发环境安装与 GOPROXY 镜像配置(含依赖管理与版本切换技巧)
  • 麒麟V10 + Docker部署KingbaseES数据库实战教程
  • 比亚迪新版五合一登陆、签到、查询、迁移
  • HOT100--Day22--74. 搜索二维矩阵,34. 在排序数组中查找元素的第一个和最后一个位置,33. 搜索旋转排序数组
  • Sentinel 原理与源码解析:流控、熔断、降级到热点限流的一体化方案
  • 克隆代币 + 捆绑开盘:多链环境下的低成本发币玩法
  • Android 项目:画图白板APP开发(六)——分页展示
  • 阿里云ClickHouse数据保护秘籍:本地备份与恢复详解
  • 数字图像处理——图像金字塔
  • 全球充电标准体系简介
  • Sub-GHz无线收发单片机,低功耗物联网通信的硬件“基石”
  • React18学习笔记(一) 创建React项目,JSX基础应用,案例:视频网站评论区
  • 【实时Linux实战系列】规避缺页中断:mlock/hugetlb 与页面预热
  • 全球汽车高压电加热器市场规模到2031年将达到62.72亿美元,CAGR 25.2%
  • 【展厅多媒体】从技术到体验,AR在展厅中的一体化整合
  • 双指针算法_移动零
  • 数据结构之复杂度
  • 几种常用锁
  • android13修改WiFi扫描二维码识别识别成功率不高的问题
  • params和body传参讲解
  • 单片机学习笔记