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

使用Python脚本删除文件夹文件时触发PermissionError错误求助

解决PermissionError: [WinError 32] 文件被占用无法删除的问题

问题根源

你的代码存在明确问题:在with代码块中打开了folder_b内的目标文件,随后直接在块内执行os.remove操作。此时文件句柄仍处于占用状态,Windows系统不允许删除正在被打开的文件,因此触发权限错误。

修复方案

将删除操作移至with代码块外部,确保文件已被自动关闭、句柄完全释放后再执行删除。修改后的compare_and_delete_sql_files函数代码如下:

def compare_and_delete_sql_files(folder_a, folder_b, output_csv, sql_filenames):
    processed_filenames = set()  # 记录已处理的文件名

    # 初始化CSV写入器
    with open(output_csv, 'w', newline='') as csvfile:
        fieldnames = ['SQL File Name', 'Occurrences', 'Match Status', 'Delete Status']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()

        # 遍历从YAML提取的SQL文件名
        for filename, occurrences in sql_filenames.items():
            if filename in processed_filenames:
                continue
            processed_filenames.add(filename)

            sql_file_a = os.path.join(folder_a, filename)
            sql_file_b = os.path.join(folder_b, filename)
            match_status = 'Not Matched'
            delete_status = 'Not Deleted'

            if os.path.exists(sql_file_a) and os.path.exists(sql_file_b):
                # 在with块内完成文件对比,退出块后文件自动关闭
                with open(sql_file_a, 'r') as f_a, open(sql_file_b, 'r') as f_b:
                    lines_a = f_a.readlines()
                    lines_b = f_b.readlines()
                    if lines_a == lines_b:
                        match_status = 'Matched'
                        delete_status = 'Deleted'
                
                # 文件已关闭,执行删除操作
                if match_status == 'Matched':
                    os.remove(sql_file_b)

            # 写入CSV记录
            writer.writerow({
                'SQL File Name': filename, 
                'Occurrences': occurrences,
                'Match Status': match_status, 
                'Delete Status': delete_status
            })

额外优化建议

  • 如果修改后仍报错,检查是否有其他进程(如文本编辑器、数据库工具)正在打开目标文件,手动关闭后重试。
  • 添加异常捕获逻辑,避免删除失败导致脚本直接崩溃:
if match_status == 'Matched':
    try:
        os.remove(sql_file_b)
    except PermissionError:
        delete_status = 'Delete Failed (File in use)'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 10:46:15