跳到主要内容

通过文件名筛选文件

功能很简单,就是按照文件名中包含的内容来筛选出文件,并移动到设置的文件夹中。

代码如下:

import os
import shutil

def move_files_by_keyword(source_dir, target_dir, keyword):
    """
    将文件名中包含指定关键字的文件移动到目标目录中。
    
    :param source_dir: 源目录路径
    :param target_dir: 目标目录路径
    :param keyword: 文件名包含的关键字
    """
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)
    
    for root, _, files in os.walk(source_dir):
        for file in files:
            if keyword in file:  # 检查文件名是否包含关键字
                source_file_path = os.path.join(root, file)
                target_file_path = os.path.join(target_dir, file)
                
                # 如果目标目录中存在同名文件,进行重命名
                if os.path.exists(target_file_path):
                    base, ext = os.path.splitext(file)
                    counter = 1
                    while os.path.exists(target_file_path):
                        new_file_name = f"{base}_{counter}{ext}"
                        target_file_path = os.path.join(target_dir, new_file_name)
                        counter += 1
                
                # 移动文件
                shutil.move(source_file_path, target_file_path)
                print(f"已移动文件: {source_file_path} -> {target_file_path}")
    
    print("符合条件的文件移动完成!")

# 示例使用
if __name__ == "__main__":
    source_directory = input("请输入源目录路径:").strip()
    target_directory = input("请输入目标目录路径:").strip()
    search_keyword = input("请输入文件名中的关键字:").strip()
    
    if os.path.exists(source_directory):
        move_files_by_keyword(source_directory, target_directory, search_keyword)
    else:
        print("源目录不存在,请检查路径!")