Python os模块文件操作完全指南:从基础到实战

张开发
2026/4/9 11:33:18 15 分钟阅读

分享文章

Python os模块文件操作完全指南:从基础到实战
在日常Python编程中文件操作是绕不开的核心技能。os模块作为Python标准库中最重要的模块之一提供了丰富的文件和目录操作方法。无论是简单的文件检测还是复杂的目录遍历os模块都能轻松胜任。本文将带你全面掌握os模块在文件操作方面的使用技巧。一、文件/目录存在性判断1.1 判断文件或目录是否存在import os # 判断路径是否存在 path example.txt if os.path.exists(path): print(f{path} 存在) else: print(f{path} 不存在) # 判断是否为文件 if os.path.isfile(path): print(f{path} 是一个文件) # 判断是否为目录 if os.path.isdir(my_folder): print(这是一个目录)1.2 获取绝对路径# 获取当前工作目录 current_dir os.getcwd() print(f当前工作目录: {current_dir}) # 转换为绝对路径 relative_path ./data/file.txt absolute_path os.path.abspath(relative_path) print(f绝对路径: {absolute_path})二、获取文件属性2.1 获取文件大小和修改时间file_path example.txt # 获取文件大小字节 file_size os.path.getsize(file_path) print(f文件大小: {file_size} 字节) # 获取文件修改时间 import time mod_time os.path.getmtime(file_path) readable_time time.ctime(mod_time) print(f最后修改时间: {readable_time}) # 获取文件创建时间Windows系统 create_time os.path.getctime(file_path) print(f创建时间: {time.ctime(create_time)})2.2 检查文件权限# 检查文件可读性 if os.access(file_path, os.R_OK): print(文件可读) # 检查文件可写性 if os.access(file_path, os.W_OK): print(文件可写) # 检查文件可执行性 if os.access(file_path, os.X_OK): print(文件可执行)三、目录遍历与操作3.1 列出目录内容# 列出目录下所有文件和子目录 all_items os.listdir(.) print(f当前目录内容: {all_items}) # 使用 scandir 获取更详细信息 with os.scandir(.) 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})3.2 递归遍历目录树# 使用 walk 递归遍历 for root, dirs, files in os.walk(.): level root.replace(., ).count(os.sep) indent * 4 * level print(f{indent}{os.path.basename(root)}/) sub_indent * 4 * (level 1) for file in files: print(f{sub_indent}{file}) # 如果需要限制遍历深度 if level 2: # 只遍历两层深度 dirs.clear() # 清空目录列表停止深入四、文件与目录操作4.1 创建目录# 创建单个目录 os.mkdir(new_folder) # 创建嵌套目录 os.makedirs(path/to/nested/folder, exist_okTrue) # 创建带权限的目录 os.makedirs(secure_folder, mode0o755) # 所有者有全部权限其他用户只有读和执行权限4.2 文件重命名与删除# 重命名文件 os.rename(old_name.txt, new_name.txt) # 重命名目录 os.rename(old_dir, new_dir) # 删除文件 os.remove(file_to_delete.txt) # 删除空目录 os.rmdir(empty_folder) # 递归删除目录及其内容 import shutil shutil.rmtree(directory_to_remove)4.3 路径操作技巧# 路径分割与连接 path /home/user/docs/report.txt # 分割路径和文件名 dirname os.path.dirname(path) # /home/user/docs basename os.path.basename(path) # report.txt # 分割文件名和扩展名 filename, extension os.path.splitext(basename) print(f文件名: {filename}, 扩展名: {extension}) # 路径连接 new_path os.path.join(dirname, data, result.csv) print(f新路径: {new_path}) # 获取路径的规范绝对路径 norm_path os.path.normpath(docs/../data/./files/../report.txt) print(f规范路径: {norm_path})五、实战应用示例5.1 批量重命名文件def batch_rename_files(directory, old_ext, new_ext): 批量修改文件扩展名 for filename in os.listdir(directory): if filename.endswith(old_ext): old_path os.path.join(directory, filename) new_filename filename.replace(old_ext, new_ext) new_path os.path.join(directory, new_filename) os.rename(old_path, new_path) print(f重命名: {filename} - {new_filename}) # 使用示例 batch_rename_files(./documents, .txt, .md)5.2 查找特定类型的文件def find_files_by_extension(directory, extension): 查找指定目录下特定扩展名的文件 result [] for root, dirs, files in os.walk(directory): for file in files: if file.endswith(extension): full_path os.path.join(root, file) result.append(full_path) return result # 查找所有Python文件 python_files find_files_by_extension(., .py) for file in python_files: print(f找到Python文件: {file})5.3 清理临时文件def cleanup_temp_files(directory, days7): 清理超过指定天数的临时文件 import time current_time time.time() cutoff_time current_time - (days * 24 * 60 * 60) for root, dirs, files in os.walk(directory): for file in files: if file.endswith(.tmp) or file.endswith(.temp): file_path os.path.join(root, file) try: # 获取文件最后修改时间 file_time os.path.getmtime(file_path) if file_time cutoff_time: os.remove(file_path) print(f已删除: {file_path}) except Exception as e: print(f删除失败 {file_path}: {e})六、高级技巧与注意事项6.1 跨平台路径处理# 使用 os.path.join 代替字符串拼接 # 不推荐 path folder / file # 不跨平台 # 推荐 path os.path.join(folder, file) # 自动处理路径分隔符 # 获取当前系统的路径分隔符 separator os.sep print(f系统路径分隔符: {separator}) # 跨平台的行分隔符 line_sep os.linesep6.2 错误处理import os import errno def safe_file_operation(filepath): try: with open(filepath, r) as f: content f.read() return content except OSError as e: if e.errno errno.ENOENT: print(f文件不存在: {filepath}) elif e.errno errno.EACCES: print(f没有权限访问: {filepath}) else: print(f其他错误: {e}) return None6.3 性能优化建议# 使用 scandir 替代 listdir性能更好 # 传统方式 items os.listdir(.) # 返回字符串列表 for item in items: full_path os.path.join(., item) if os.path.isdir(full_path): print(f目录: {item}) # 优化方式 with os.scandir(.) as entries: for entry in entries: if entry.is_dir(): # 不需要stat调用 print(f目录: {entry.name})总结os模块是Python文件操作的核心工具提供了丰富的功能来管理文件和目录。本文介绍了从基础的文件存在性检查到高级的目录遍历操作以及在实际开发中的常见应用场景。掌握这些知识你将能够熟练进行文件和目录的创建、删除、重命名安全地处理跨平台路径问题高效地遍历和搜索文件系统实现自动化的文件管理任务记住在实际开发中结合shutil、pathlib等模块Python 3.4推荐使用pathlib可以让文件操作更加便捷和安全。始终注意添加适当的错误处理确保代码的健壮性。

更多文章