概述
Python提供了多种灵活的方法来进行智能化的文件移动与分类管理,其中可以使用shutil和os模块来根据文件的扩展名、关键词、日期进行文件的移动与分类。以下是一些常见的方法和示例。
代码示例实现
基本文件移动
import shutil
import os
# 移动单个文件
def move_file(source_path, destination_path):
try:
shutil.move(source_path, destination_path)
print(f"文件已移动: {source_path} -> {destination_path}")
except Exception as e:
print(f"移动文件时出错: {e}")
# 示例
source = "path/to/source/file.txt"
destination = "path/to/destination/file.txt"
move_file(source, destination)
根据扩展名分类文件
import os
import shutil
from pathlib import Path
def classify_by_extension(source_dir, target_dir):
"""
根据文件扩展名分类文件
"""
# 确保目标目录存在
Path(target_dir).mkdir(parents=True, exist_ok=True)
for filename in os.listdir(source_dir):
source_path = os.path.join(source_dir, filename)
# 跳过目录,只处理文件
if os.path.isfile(source_path):
# 获取文件扩展名(去掉点)
extension = Path(filename).suffix[1:].lower() # 转为小写
if extension: # 如果有扩展名
# 创建扩展名子目录
ext_dir = os.path.join(target_dir, extension)
Path(ext_dir).mkdir(parents=True, exist_ok=True)
# 移动文件
destination_path = os.path.join(ext_dir, filename)
shutil.move(source_path, destination_path)
print(f"已移动: {filename} -> {ext_dir}/")
else:
print(f"跳过无扩展名文件: {filename}")
# 示例使用
classify_by_extension("path/to/source", "path/to/destination")
根据关键词分类文件
import os
import shutil
from pathlib import Path
def classify_by_keywords(source_dir, target_dir, keyword_categories):
"""
根据文件名中的关键词分类文件
keyword_categories: 字典,键为分类名,值为关键词列表
"""
Path(target_dir).mkdir(parents=True, exist_ok=True)
for filename in os.listdir(source_dir):
source_path = os.path.join(source_dir, filename)
if os.path.isfile(source_path):
file_moved = False
for category, keywords in keyword_categories.items():
# 检查文件名是否包含该类别的任何关键词
if any(keyword.lower() in filename.lower() for keyword in keywords):
# 创建分类目录
category_dir = os.path.join(target_dir, category)
Path(category_dir).mkdir(parents=True, exist_ok=True)
# 移动文件
destination_path = os.path.join(category_dir, filename)
shutil.move(source_path, destination_path)
print(f"已移动: {filename} -> {category}/")
file_moved = True
break
if not file_moved:
# 如果没有匹配任何分类,移动到"其他"目录
other_dir = os.path.join(target_dir, "其他")
Path(other_dir).mkdir(parents=True, exist_ok=True)
destination_path = os.path.join(other_dir, filename)
shutil.move(source_path, destination_path)
print(f"已移动: {filename} -> 其他/")
# 示例使用
keyword_categories = {
"图片": ["photo", "image", "pic", "截图"],
"文档": ["doc", "report", "论文", "文档"],
"代码": ["code", "program", "script", "python"],
"视频": ["video", "movie", "录像"]
}
classify_by_keywords("path/to/source", "path/to/destination", keyword_categories)
根据日期分类文件
import os
import shutil
from pathlib import Path
from datetime import datetime
def classify_by_date(source_dir, target_dir, date_format="%Y-%m"):
"""
根据文件修改日期分类文件
date_format: 日期格式,如 "%Y"(年)、"%Y-%m"(年月)、"%Y-%m-%d"(年月日)
"""
Path(target_dir).mkdir(parents=True, exist_ok=True)
for filename in os.listdir(source_dir):
source_path = os.path.join(source_dir, filename)
if os.path.isfile(source_path):
# 获取文件修改时间
modify_time = os.path.getmtime(source_path)
date_str = datetime.fromtimestamp(modify_time).strftime(date_format)
# 创建日期目录
date_dir = os.path.join(target_dir, date_str)
Path(date_dir).mkdir(parents=True, exist_ok=True)
# 移动文件
destination_path = os.path.join(date_dir, filename)
shutil.move(source_path, destination_path)
print(f"已移动: {filename} -> {date_str}/")
# 示例使用
classify_by_date("path/to/source", "path/to/destination", "%Y-%m") # 按年月分类
安全移动函数(避免覆盖)
import os
import shutil
from pathlib import Path
def safe_move_file(source_path, destination_dir, filename=None):
"""
安全移动文件,避免文件名冲突
"""
if filename is None:
filename = os.path.basename(source_path)
destination_path = os.path.join(destination_dir, filename)
# 如果目标文件已存在,在文件名后添加数字
counter = 1
name, ext = os.path.splitext(filename)
while os.path.exists(destination_path):
new_filename = f"{name}_{counter}{ext}"
destination_path = os.path.join(destination_dir, new_filename)
counter += 1
shutil.move(source_path, destination_path)
return destination_path
注意事项
- 备份数据:在运行文件移动操作前,最好先备份重要文件
- 权限问题:确保有足够的权限读写相关目录
- 路径处理:使用os.path.join()来处理路径,避免跨平台兼容性
- 问题异常处理:添加适当的异常处理来应对各种错误情况
这些函数可以根据你的具体需求进行修改和组合使用,实现灵活的文件分类和移动功能。

被折叠的 条评论
为什么被折叠?



