You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python从多文件夹移动特定命名模式的多个文件

问题解决方法

核心问题分析

原代码里的"Indeks-Standar-Pencemar-Udara-di-SPKU-Bulan*" in file是错误逻辑——这里把*当成了普通字符串的一部分去匹配,但实际你需要的是通配符模糊匹配,所以这个条件永远不会成立,自然没有文件被移动。

修正后的代码

import os
from fnmatch import fnmatch

target_folder = r"C:\Users\EVOSYS\Documents\PROJECT-ISPU-DKI-JAKARTA-main\File Gabungan ISPU di SPKU 2010 - 2021"
source_folder = r"C:\Users\EVOSYS\Documents\PROJECT-ISPU-DKI-JAKARTA-main"

# 确保目标文件夹存在,避免报错
if not os.path.exists(target_folder):
    os.makedirs(target_folder)

for path, _, files in os.walk(source_folder):
    for file in files:
        # 使用fnmatch处理通配符匹配
        if fnmatch(file, "Indeks-Standar-Pencemar-Udara-di-SPKU-Bulan*"):
            source_path = os.path.join(path, file)
            target_path = os.path.join(target_folder, file)
            
            # 检查目标路径是否已有同名文件,避免覆盖
            if not os.path.exists(target_path):
                os.rename(source_path, target_path)
            else:
                # 重名时自动添加数字后缀区分
                count = 1
                while True:
                    name_part, ext_part = os.path.splitext(file)
                    new_filename = f"{name_part}_{count}{ext_part}"
                    new_target_path = os.path.join(target_folder, new_filename)
                    if not os.path.exists(new_target_path):
                        os.rename(source_path, new_target_path)
                        break
                    count += 1

关键改进点

  • 用fnmatch.fnmatch()处理通配符匹配,符合你需要的*模糊匹配需求
  • 用os.path.join()拼接路径,避免手动加\导致的路径格式错误
  • 增加目标文件夹自动创建逻辑,防止因文件夹不存在报错
  • 处理重名文件的情况,避免直接覆盖已有文件

内容的提问来源于stack exchange,提问作者Diaz Jubairy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 16:35:26