首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Python 自动化文件管理的10个模板

Python 自动化文件管理的10个模板

作者头像
用户11081884
发布2026-07-20 17:11:19
发布2026-07-20 17:11:19
470
举报

Python提供了丰富的库和工具来帮助自动化文件管理任务。本文将介绍10个实用的Python文件管理脚本模板,让文件管理工作变得更加高效和轻松。

1. 递归遍历目录结构

代码语言:javascript
复制
import os

def walk_directory(directory):
    """递归遍历目录及其子目录"""
    for root, dirs, files in os.walk(directory):
        print(f"当前目录: {root}")
        print(f"子目录: {dirs}")
        print(f"文件: {files}")
        print("-" * 40)

模板使用 os.walk() 函数递归遍历指定目录及其所有子目录,返回当前目录路径、子目录列表和文件列表。

2. 批量重命名文件

代码语言:javascript
复制
import os

def batch_rename(directory, prefix):
    """批量添加前缀重命名文件"""
    for count, filename in enumerate(os.listdir(directory)):
        if os.path.isfile(os.path.join(directory, filename)):
            new_name = f"{prefix}_{count+1}{os.path.splitext(filename)[1]}"
            os.rename(
                os.path.join(directory, filename),
                os.path.join(directory, new_name)
            )
            print(f"重命名: {filename} -> {new_name}")

脚本可以为目录中的所有文件添加统一前缀并按顺序编号,非常适合整理照片或文档。

3. 查找重复文件

代码语言:javascript
复制
import os
import hashlib

def find_duplicate_files(directory):
    """查找目录中的重复文件"""
    file_hashes = {}
    duplicates = []
    
    for root, _, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            with open(file_path, 'rb') as f:
                file_hash = hashlib.md5(f.read()).hexdigest()
            if file_hash in file_hashes:
                duplicates.append((file_path, file_hashes[file_hash]))
            else:
                file_hashes[file_hash] = file_path
    
    return duplicates

通过计算文件的MD5哈希值,这个脚本可以找出目录中内容完全相同的重复文件。

4. 批量转换文件编码

代码语言:javascript
复制
def convert_file_encoding(input_file, output_file, from_encoding, to_encoding):
    """转换文件编码格式"""
    with open(input_file, 'r', encoding=from_encoding) as f_in:
        content = f_in.read()
    with open(output_file, 'w', encoding=to_encoding) as f_out:
        f_out.write(content)

def batch_convert_encoding(directory, from_encoding, to_encoding):
    """批量转换目录下所有文件的编码"""
    for root, _, files in os.walk(directory):
        for file in files:
            input_path = os.path.join(root, file)
            output_path = os.path.join(root, f"converted_{file}")
            convert_file_encoding(input_path, output_path, from_encoding, to_encoding)
            print(f"已转换: {input_path}")

模板特别适合处理不同编码的文本文件,如将GB2312编码的文件批量转换为UTF-8

5. 文件内容搜索工具

代码语言:javascript
复制
def search_in_files(directory, search_text):
    """在文件中搜索特定文本"""
    results = []
    for root, _, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    for line_num, line in enumerate(f, 1):
                        if search_text in line:
                            results.append({
                                'file': file_path,
                                'line': line_num,
                                'content': line.strip()
                            })
            except UnicodeDecodeError:
                continue  # 跳过二进制文件
    return results

脚本可以在指定目录的所有文本文件中搜索特定内容,并返回匹配的文件名、行号和内容。

6. 自动备份重要文件

代码语言:javascript
复制
import shutil
from datetime import datetime

def backup_files(source_dir, backup_dir):
    """自动备份文件到指定目录"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_path = os.path.join(backup_dir, f"backup_{timestamp}")
    
    if not os.path.exists(backup_path):
        os.makedirs(backup_path)
    
    for item in os.listdir(source_dir):
        source = os.path.join(source_dir, item)
        if os.path.isfile(source):
            shutil.copy2(source, backup_path)
            print(f"已备份: {item}")

模板可以定期备份重要文件到指定目录,并按时间戳创建不同的备份版本。

7. 文件类型统计

代码语言:javascript
复制
from collections import defaultdict

def file_type_statistics(directory):
    """统计目录中各种文件类型的数量"""
    stats = defaultdict(int)
    for root, _, files in os.walk(directory):
        for file in files:
            ext = os.path.splitext(file)[1].lower()
            stats[ext if ext else '无扩展名'] += 1
    return dict(stats)

脚本可以统计目录中各种文件类型的数量,帮助你了解文件分布情况。

8. 自动整理下载文件夹

代码语言:javascript
复制
def organize_downloads(download_dir):
    """自动整理下载文件夹"""
    categories = {
        '图片': ['.jpg', '.jpeg', '.png', '.gif', '.bmp'],
        '文档': ['.pdf', '.docx', '.xlsx', '.pptx', '.txt'],
        '压缩包': ['.zip', '.rar', '.7z', '.tar', '.gz'],
        '音频': ['.mp3', '.wav', '.flac'],
        '视频': ['.mp4', '.avi', '.mkv', '.mov']
    }
    
    for category, extensions in categories.items():
        category_dir = os.path.join(download_dir, category)
        if not os.path.exists(category_dir):
            os.makedirs(category_dir)
        
        for file in os.listdir(download_dir):
            if os.path.isfile(os.path.join(download_dir, file)):
                ext = os.path.splitext(file)[1].lower()
                if ext in extensions:
                    shutil.move(
                        os.path.join(download_dir, file),
                        os.path.join(category_dir, file)
                    )
                    print(f"已移动: {file} -> {category}")

模板可以自动将下载文件夹中的文件按类型分类到不同的子目录中。

9. 文件权限批量修改

代码语言:javascript
复制
import stat

def change_file_permissions(directory, permission_mode):
    """批量修改文件权限"""
    for root, _, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            os.chmod(file_path, permission_mode)
            print(f"已修改权限: {file_path}")

脚本可以批量修改目录中所有文件的权限,适用于Linux/Unix系统。

10. 自动同步两个目录

代码语言:javascript
复制
def sync_directories(source_dir, target_dir):
    """同步两个目录的内容"""
    for root, dirs, files in os.walk(source_dir):
        relative_path = os.path.relpath(root, source_dir)
        target_path = os.path.join(target_dir, relative_path)
        
        if not os.path.exists(target_path):
            os.makedirs(target_path)
            print(f"创建目录: {target_path}")
        
        for file in files:
            source_file = os.path.join(root, file)
            target_file = os.path.join(target_path, file)
            
            if not os.path.exists(target_file) or \
               os.path.getmtime(source_file) > os.path.getmtime(target_file):
                shutil.copy2(source_file, target_file)
                print(f"同步文件: {file}")

模板可以实现两个目录之间的自动同步,保持目标目录与源目录内容一致。

应用:自动化照片管理

假设需要管理大量照片,可以结合多个模板:

1、使用get_image_files遍历照片目

2、使用organize_downloads按年份分类照片

3、使用find_duplicates查找重复照片

4、使用create_compressed_archive创建照片压缩包

5、使用generate_thumbnails生成缩略图

6、使用rename_sequential批量重命名

通过组合这些模板可以构建一个完整的照片管理系统。

代码语言:javascript
复制
import os
import shutil
from datetime import datetime
from PIL import Image
import hashlib
import zipfile

class PhotoLibraryManager:
    def __init__(self, source_dir):
        self.source_dir = source_dir
        self.image_extensions = ('.png', '.jpg', '.jpeg', '.gif', '.bmp')
        
    def get_image_files(self):
        """获取目录中所有图片文件路径[6](@ref)"""
        images = []
        for root, _, files in os.walk(self.source_dir):
            for file in files:
                if file.lower().endswith(self.image_extensions):
                    images.append(os.path.join(root, file))
        return images
    
    def organize_by_date(self, output_dir):
        """
        按拍摄日期整理照片[4](@ref)
        改进点:同时处理EXIF日期和文件修改日期
        """
        os.makedirs(output_dir, exist_ok=True)
        
        for img_path in self.get_image_files():
            try:
                with Image.open(img_path) as img:
                    # 尝试从EXIF获取拍摄日期
                    exif = img._getexif()
                    date_taken = exif.get(36867) if exif else None
                    
                    if date_taken:
                        date_obj = datetime.strptime(date_taken, '%Y:%m:%d %H:%M:%S')
                    else:
                        # 使用文件修改日期作为备选
                        mtime = os.path.getmtime(img_path)
                        date_obj = datetime.fromtimestamp(mtime)
                    
                    date_str = date_obj.strftime('%Y-%m')
                    dest_dir = os.path.join(output_dir, date_str)
                    os.makedirs(dest_dir, exist_ok=True)
                    shutil.copy2(img_path, os.path.join(dest_dir, os.path.basename(img_path)))
            except Exception as e:
                print(f"处理文件 {img_path} 时出错: {e}")

    def find_duplicates(self):
        """查找重复图片(基于MD5哈希)[3](@ref)[6](@ref)"""
        hashes = {}
        duplicates = []
        
        for img_path in self.get_image_files():
            with open(img_path, 'rb') as f:
                file_hash = hashlib.md5(f.read()).hexdigest()
            
            if file_hash in hashes:
                duplicates.append((img_path, hashes[file_hash]))
            else:
                hashes[file_hash] = img_path
        return duplicates

    def create_compressed_archive(self, output_path, year=None):
        """
        创建压缩归档文件[6](@ref)[7](@ref)
        改进点:支持按年份归档
        """
        with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for img_path in self.get_image_files():
                if year and not str(year) in os.path.basename(img_path):
                    continue
                zipf.write(img_path, os.path.basename(img_path))

    def generate_thumbnails(self, thumb_dir, size=(200, 200)):
        """生成缩略图[2](@ref)[5](@ref)"""
        os.makedirs(thumb_dir, exist_ok=True)
        
        for img_path in self.get_image_files():
            try:
                with Image.open(img_path) as img:
                    img.thumbnail(size)
                    thumb_path = os.path.join(thumb_dir, f"thumb_{os.path.basename(img_path)}")
                    img.save(thumb_path)
            except Exception as e:
                print(f"生成缩略图失败: {img_path} - {e}")

    def rename_sequential(self, prefix="photo", output_dir=None):
        """批量顺序重命名[5](@ref)[7](@ref)"""
        output_dir = output_dir or self.source_dir
        os.makedirs(output_dir, exist_ok=True)
        
        for i, img_path in enumerate(self.get_image_files(), 1):
            ext = os.path.splitext(img_path)[1]
            new_name = f"{prefix}_{i:04d}{ext}"
            shutil.copy2(img_path, os.path.join(output_dir, new_name))

# 使用示例
if __name__ == "__main__":
    manager = PhotoLibraryManager("~/Photos")
    
    # 1. 按日期整理
    manager.organize_by_date("~/Photos_Organized")    
    # 2. 查找并显示重复图片
    duplicates = manager.find_duplicates()
    for dup in duplicates:
        print(f"重复文件: {dup[0]} 和 {dup[1]}")    
    # 3. 创建年度压缩包
    manager.create_compressed_archive("~/Photos_Backup_2025.zip", year=2025)    
    # 4. 生成缩略图
    manager.generate_thumbnails("~/Photos/Thumbnails")   
    # 5. 批量重命名
    manager.rename_sequential("vacation", "~/Photos/Renamed")

本文10个实用的Python文件管理脚本模板,涵盖了从基本文件操作到高级自动化管理的各个方面。自动化文件管理不仅能节省大量时间,还能减少人为错误。将它们集成到更大的自动化工作流程中,根据具体需求进行组合和修改,帮助高效地完成各种文件管理任务。

“无他,惟手熟尔”!有需要的用起来。

如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!😊

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-08-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Nicholas与Pypi 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 递归遍历目录结构
  • 2. 批量重命名文件
  • 3. 查找重复文件
  • 4. 批量转换文件编码
  • 5. 文件内容搜索工具
  • 6. 自动备份重要文件
  • 7. 文件类型统计
  • 8. 自动整理下载文件夹
  • 9. 文件权限批量修改
  • 10. 自动同步两个目录
  • 应用:自动化照片管理
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档