基于文件名部分内容筛选并移动文件的Python实现求助
问题:筛选并移动符合规则的文件
文件示例
my_floder: Review Report - 2020-3.20230110151743889.xlsx Review Report - 2020-3.20230110151753535.xlsx Review Report - 2019-4.20230110151744423.xlsx
文件名拆分规则
以第一个文件为例,拆分后:
第一部分:"Review Report -" 第二部分:"2020-3" 第三部分:".20230110151743889"
需求逻辑
- 若多个文件的第二部分相同,仅保留第三部分(
yyyymmddhhmm格式时间戳)值最大的文件 - 将筛选后的文件移动到目标文件夹
- 示例中,前两个文件第二部分相同,第二个文件第三部分更大,因此仅移动第二个和第三个文件
可用代码片段
拆分文件名的代码及输出:
parts_list=os.path.basename(filename).split(".") # 输出:['Review Report - 2020-3', '20230110151743889', 'xlsx'] second_part = parts_list[0].split(" - ")[1] # 输出:'2020-3' third_part=parts_list[1] # 输出:'20230110151743889'
现有代码(待完善)
unique = [] for filename in glob.glob(my_floder): parts_list=os.path.basename(filename).split(".") second_part = parts_list[0].split(" - ")[1] third_part=parts_list[1] if second_part not in unique: unique.append(second_part) else: # 此处需比较第三部分的值,移动第三部分更大的文件,但不知如何实现
完善后的代码
思路:用字典存储每个second_part对应的最大时间戳文件,遍历所有文件后,字典中的值即为需要移动的目标文件。
import os import glob import shutil # 源文件夹匹配规则(需包含文件后缀,比如指定xlsx类型) source_pattern = "my_floder/*.xlsx" # 目标文件夹路径,不存在则自动创建 target_folder = "target_floder" if not os.path.exists(target_folder): os.makedirs(target_folder) # 存储每个second_part对应的最大时间戳文件 file_dict = {} for filename in glob.glob(source_pattern): parts_list = os.path.basename(filename).split(".") second_part = parts_list[0].split(" - ")[1] third_part = parts_list[1] # 首次遇到该second_part,直接存入字典 if second_part not in file_dict: file_dict[second_part] = (third_part, filename) else: # 对比当前文件与已存储文件的时间戳,保留更大的 stored_third, stored_file = file_dict[second_part] if third_part > stored_third: file_dict[second_part] = (third_part, filename) # 执行文件移动操作 for _, (_, file_to_move) in file_dict.items(): target_path = os.path.join(target_folder, os.path.basename(file_to_move)) shutil.move(file_to_move, target_path)
说明
- 用字典一次性记录每个分组的最优文件,避免重复遍历
- 时间戳为固定格式字符串,直接通过字符串比较即可判断大小
- 自动创建目标文件夹,避免路径不存在报错
- 使用
shutil.move完成跨文件夹的文件移动
内容的提问来源于stack exchange,提问作者William
相关产品推荐
相关产品推荐

