上一篇
Python文件目录操作的重要性
在编程中,文件和目录操作是日常任务的核心部分。无论是数据清洗、日志处理还是自动化脚本,Python提供了强大而灵活的工具来管理文件系统。本教程将深入探讨Python中用于文件和目录操作的核心模块和方法。
关键要点: Python主要通过两个模块处理文件和目录操作:
os
模块用于基本操作,shutil
模块用于高级文件操作。
核心模块介绍
os模块
提供与操作系统交互的功能,包括文件/目录的创建、删除、重命名、路径操作等基础功能。
shutil模块
提供高级文件操作功能,包括文件/目录的复制、移动、归档(压缩/解压)等。
pathlib模块
Python 3.4+引入的面向对象的路径操作方式,提供更直观的路径操作方法。
目录操作常用方法
1. 创建目录
Python提供多种创建目录的方法:
# 导入os模块
import os
# 创建单个目录
os.mkdir("new_directory")
# 创建多级目录(如果父目录不存在会自动创建)
os.makedirs("parent/child/grandchild", exist_ok=True)
# 使用pathlib创建目录(Python 3.5+)
from pathlib import Path
Path("another_directory").mkdir(parents=True, exist_ok=True)
import os
# 创建单个目录
os.mkdir("new_directory")
# 创建多级目录(如果父目录不存在会自动创建)
os.makedirs("parent/child/grandchild", exist_ok=True)
# 使用pathlib创建目录(Python 3.5+)
from pathlib import Path
Path("another_directory").mkdir(parents=True, exist_ok=True)
2. 删除目录
删除目录时需注意权限和目录状态:
# 删除空目录
os.rmdir("empty_directory")
# 删除目录及其所有内容(使用shutil)
import shutil
shutil.rmtree("directory_with_content")
# 安全删除(检查目录是否存在)
if os.path.exists("old_directory"):
shutil.rmtree("old_directory")
os.rmdir("empty_directory")
# 删除目录及其所有内容(使用shutil)
import shutil
shutil.rmtree("directory_with_content")
# 安全删除(检查目录是否存在)
if os.path.exists("old_directory"):
shutil.rmtree("old_directory")
3. 目录遍历与文件搜索
遍历目录是文件处理中的常见任务:
# 列出目录内容
files = os.listdir("my_directory")
print(files) # 输出文件和目录列表
# 递归遍历目录(使用os.walk)
for root, dirs, files in os.walk("project"):
print(f"当前目录: {root}")
print(f"子目录: {dirs}")
print(f"文件: {files}")
# 使用glob模式匹配文件
import glob
python_files = glob.glob("src/**/*.py", recursive=True)
files = os.listdir("my_directory")
print(files) # 输出文件和目录列表
# 递归遍历目录(使用os.walk)
for root, dirs, files in os.walk("project"):
print(f"当前目录: {root}")
print(f"子目录: {dirs}")
print(f"文件: {files}")
# 使用glob模式匹配文件
import glob
python_files = glob.glob("src/**/*.py", recursive=True)
文件操作常用方法
1. 文件创建与读写
# 创建并写入文件
with open("new_file.txt", "w") as f:
f.write("Hello, Python File Operations!")
# 读取文件内容
with open("new_file.txt", "r") as f:
content = f.read()
print(content)
# 追加内容到文件
with open("new_file.txt", "a") as f:
f.write("\nAppending more text!")
with open("new_file.txt", "w") as f:
f.write("Hello, Python File Operations!")
# 读取文件内容
with open("new_file.txt", "r") as f:
content = f.read()
print(content)
# 追加内容到文件
with open("new_file.txt", "a") as f:
f.write("\nAppending more text!")
2. 文件复制与移动
# 复制文件(使用shutil)
shutil.copy("source.txt", "destination.txt")
# 复制文件并保留元数据
shutil.copy2("source.txt", "backup/source.txt")
# 移动/重命名文件
shutil.move("old_name.txt", "new_name.txt")
os.rename("old_file.txt", "new_file.txt")
shutil.copy("source.txt", "destination.txt")
# 复制文件并保留元数据
shutil.copy2("source.txt", "backup/source.txt")
# 移动/重命名文件
shutil.move("old_name.txt", "new_name.txt")
os.rename("old_file.txt", "new_file.txt")
3. 文件信息与权限
# 获取文件信息
file_stats = os.stat("important_document.pdf")
print(f"大小: {file_stats.st_size} bytes")
print(f"修改时间: {file_stats.st_mtime}")
# 修改文件权限
os.chmod("script.py", 0o755) # 设置为可执行
# 检查路径类型
print(os.path.isfile("data.csv")) # True
print(os.path.isdir("reports")) # True
print(os.path.exists("missing.txt")) # False
file_stats = os.stat("important_document.pdf")
print(f"大小: {file_stats.st_size} bytes")
print(f"修改时间: {file_stats.st_mtime}")
# 修改文件权限
os.chmod("script.py", 0o755) # 设置为可执行
# 检查路径类型
print(os.path.isfile("data.csv")) # True
print(os.path.isdir("reports")) # True
print(os.path.exists("missing.txt")) # False
综合应用示例
项目目录清理脚本
以下脚本清理项目目录中的临时文件,并归档日志文件:
import os
import shutil
from datetime import datetime
# 清理临时文件
for root, dirs, files in os.walk("project"):
for file in files:
if file.endswith(".tmp") or file.endswith(".temp"):
os.remove(os.path.join(root, file))
# 归档旧日志文件
archive_dir = "logs/archive"
os.makedirs(archive_dir, exist_ok=True)
# 移动30天前的日志文件
for log_file in os.listdir("logs"):
if log_file.endswith(".log"):
file_path = os.path.join("logs", log_file)
file_age = datetime.now() - datetime.fromtimestamp(os.path.getmtime(file_path))
if file_age.days > 30:
shutil.move(file_path, os.path.join(archive_dir, log_file))
print("项目清理和归档完成!")
import shutil
from datetime import datetime
# 清理临时文件
for root, dirs, files in os.walk("project"):
for file in files:
if file.endswith(".tmp") or file.endswith(".temp"):
os.remove(os.path.join(root, file))
# 归档旧日志文件
archive_dir = "logs/archive"
os.makedirs(archive_dir, exist_ok=True)
# 移动30天前的日志文件
for log_file in os.listdir("logs"):
if log_file.endswith(".log"):
file_path = os.path.join("logs", log_file)
file_age = datetime.now() - datetime.fromtimestamp(os.path.getmtime(file_path))
if file_age.days > 30:
shutil.move(file_path, os.path.join(archive_dir, log_file))
print("项目清理和归档完成!")
最佳实践与注意事项
- 总是使用
with
语句处理文件,确保资源正确释放 - 操作前检查文件/目录是否存在(
os.path.exists
) - 处理路径时使用
os.path.join
保证跨平台兼容性 - 删除操作前进行二次确认,特别是使用
shutil.rmtree
- 处理用户输入路径时,防范路径遍历攻击
- 考虑使用
pathlib
获得更面向对象的路径操作体验
安全提示: 当处理用户提供的文件路径时,务必进行验证和清理,防止路径遍历攻击(如../../../etc/passwd)。
发表评论