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

解决Python遍历目录存Excel的MemoryError,实现指定列文件清单存储

解决遍历目录文件写入Excel时的MemoryError问题

当遍历大量目录及文件时,一次性将所有文件信息存入内存再写入Excel会触发MemoryError。下面的代码通过逐行写入Excel的方式避免内存过载,同时完成需求:

实现代码

import os
from openpyxl import Workbook

def write_files_to_excel(root_dir, output_excel):
    # 创建工作簿和工作表
    wb = Workbook()
    ws = wb.active
    # 设置表头
    ws.append(["Index", "Header", "Path", "File Name"])
    
    index = 1
    # 遍历目录及子目录
    for dirpath, _, filenames in os.walk(root_dir):
        for filename in filenames:
            try:
                # 构造文件完整路径
                full_path = os.path.join(dirpath, filename)
                # 写入当前文件信息(Header可根据需求自定义,这里用目录名示例)
                ws.append([index, os.path.basename(dirpath), dirpath, filename])
                index += 1
                # 每写入1000行保存一次(可选,进一步降低内存压力)
                if index % 1000 == 0:
                    wb.save(output_excel)
            except PermissionError:
                # 跳过无权限访问的文件
                print(f"无权限访问文件:{full_path}")
                continue
            except Exception as e:
                # 捕获其他异常并打印
                print(f"处理文件{full_path}时出错:{str(e)}")
                continue
    # 最终保存文件
    wb.save(output_excel)
    print(f"文件已成功保存至:{output_excel}")

# 使用示例
if __name__ == "__main__":
    target_directory = "/path/to/your/target/directory"  # 替换为目标目录
    output_file = "file_list.xlsx"  # 输出Excel文件名
    write_files_to_excel(target_directory, output_file)

关键优化点

  • 逐行写入:遍历到文件就立即写入Excel,不将所有文件信息缓存到内存中,大幅降低内存占用
  • 可选分批保存:每写入1000行就保存一次,避免openpyxl在内存中暂存过多未保存数据
  • 异常处理:跳过无权限访问的文件,避免程序中断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:06:10