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

如何用Python将多个.txt文件合并为单个.csv文件?

求助:把4000个TXT文件合并成带文件名和内容的CSV

我现在有个文件夹,里面大概有4000个.txt文件,想把它们合并成一个单独的.csv文件,这个CSV需要有两列:

  • 第一列叫File Name,要和原文件夹里的文件名完全一致
  • 第二列叫Content,要包含对应TXT文件里的所有文本内容

我在Stack Overflow上找了最相似的问题,但试了里面的所有办法都没成功。最后试了其中Nathaniel Verhaaren写的Python代码,哪怕参考评论里的建议改了改,还是碰到和原作者一模一样的错误,代码如下:

import os
import csv
dirpath = 'path_of_directory'
output = 'output_file.csv'
with open(output, 'w') as outfile:
    csvout = csv.writer(outfile)
    csvout.writerow(['FileName', 'Content'])
    files = os.listdir(dirpath)
    for filename in files:
        with open(dirpath + '/' + filename) as afile:
            csvout.writerow([filename, afile.read()])
        afile.close()
outfile.close()

另外我还看了几个其他类似的Stack Overflow问题,但它们的解决方案要么不匹配我的需求,要么我没法调整成适合我用的样子,实在没办法了来求助。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:49:36