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

删除已存在合并文件后重新创建时出错,求解决方案

解决删除合并文件后重新创建报错的问题

问题根源

  1. 你的代码在遍历文件后缀时,提前通过glob.glob获取了所有对应后缀的文件列表——如果之前生成过merged.xlsx/merged.csv,这个文件会被包含在all_files里。当你删除该文件后调用合并函数,函数依然会尝试读取那个已被删除的文件路径,直接触发报错。
  2. 把mergeExcelCsv函数定义在for循环内部属于不规范写法,容易引发变量绑定的隐性问题。

修正方案

  1. 将合并函数移到循环外部,通过参数传递所需变量,避免循环内定义函数的风险。
  2. 在处理完文件覆盖(删除旧文件)后,重新获取最新的文件列表,确保只包含当前目录下的有效文件,同时排除合并后的目标文件本身,防止循环合并。
  3. 优化条件判断逻辑,减少冗余代码。

修正后的完整代码

from tkinter.filedialog import askdirectory
from tkinter import messagebox
import os
import glob
import pandas as pd

def mergeExcelCsv(all_files, merged_path, ext):
    if ext == ".xlsx":
        df = pd.concat([pd.read_excel(a, header=None) for a in all_files], ignore_index=True)
        df.to_excel(merged_path, index=False)
    elif ext == ".csv":
        df = pd.concat([pd.read_csv(a, header=None, sep=',') for a in all_files], ignore_index=True)
        df.to_csv(merged_path, index=False)

files_directory = askdirectory(title='选择文件夹')
merged_file_name = "merged"
files_extension = [".xlsx", ".csv"]

if files_directory != '':
    for ext in files_extension:
        merged_files = os.path.join(files_directory, merged_file_name + ext)
        proceed = False
        
        if os.path.exists(merged_files):
            filename_only = os.path.split(merged_files)[1]
            message = f"{filename_only} 已存在,是否覆盖?"
            msgbox = messagebox.askquestion("文件已存在", message, icon='warning')
            if msgbox == 'yes':
                os.remove(merged_files)
                messagebox.showinfo('文件覆盖', '文件已覆盖!')
                proceed = True
            else:
                continue
        else:
            proceed = True
        
        if proceed:
            # 重新获取当前目录下的对应后缀文件
            files_pattern = os.path.join(files_directory, "*" + ext)
            all_files = glob.glob(files_pattern)
            # 排除合并目标文件,避免循环合并
            all_files = [f for f in all_files if f != merged_files]
            
            if not all_files:
                messagebox.showinfo('提示', f"未找到任何{ext}格式的文件")
                continue
            
            mergeExcelCsv(all_files, merged_files, ext)
else:
    pass

额外说明

  • 新增了空文件列表判断,当目录下没有对应后缀的文件时,会弹出提示,避免无意义的合并操作。
  • 严格排除合并后的目标文件,确保每次合并的都是原始的数据源文件,不会出现重复合并的问题。

内容的提问来源于stack exchange,提问作者David L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:57:15