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

Python合并文件夹TSV文件并添加文件名列报错求助

解决TSV文件合并时的FileNotFoundError问题

问题场景

我有多个TSV文件(如2018Q1.tsv、2018Q2.tsv等),文件内每行用\n分隔,字段用|分隔。需要用Python将这些文件合并为一个文件,并把文件名作为新增的Date列。

我编写了如下代码:

import os
import pandas as pd
#read the path
cwd = os.path.abspath(r'path/to/directory')
#list all the files from the directory
file_list = os.listdir(cwd)
file_list

columns = ['CIK_number', 'Companyname', 'FilingType', 'Filingdate', 'filingtext', 'filingurl']

for file in file_list:
    (pd.concat({f.rsplit('.')[0]: pd.read_csv(f, sep='|', header=None, names=columns)
            for f in file_list}, names=['Date'])
   .reset_index(0)
   .to_csv('output_file.tsv', index=False)
)

预期合并后输出样例:

Date,CIK_number,Companyname,FilingType,Filingdate,filingtext,filingurl
2018Q1,860585,RBS PARTNERS L P /CT,13FCONP,1993-02-11,edgar/data/860585/9999999997-04-035713.txt,edgar/data/860585/9999999997-04-035713-index.html
2018Q2,926688,SMITH THOMAS W,13F-HR,1993-02-12,edgar/data/926688/9999999997-05-015654.txt,edgar/data/926688/9999999997-05-015654-index.html

但运行时出现FileNotFoundError,提示找不到文件'1993-QTR1.tsv',无法完成合并。

错误原因

  1. 文件路径不完整:os.listdir(cwd)仅返回文件名,而非完整路径。执行pd.read_csv(f)时,Python会在当前工作目录(而非你指定的cwd)查找文件,导致找不到目标文件。
  2. 多余循环:外层for file in file_list完全冗余,会重复执行合并逻辑多次,最终覆盖输出文件。

修正后的代码

import os
import pandas as pd

# 目标文件夹路径
cwd = os.path.abspath(r'path/to/directory')
# 获取所有TSV文件的完整路径,过滤非TSV文件
file_list = [os.path.join(cwd, f) for f in os.listdir(cwd) if f.endswith('.tsv')]

columns = ['CIK_number', 'Companyname', 'FilingType', 'Filingdate', 'filingtext', 'filingurl']

# 构建文件名与对应DataFrame的字典
df_dict = {}
for full_path in file_list:
    # 提取文件名(不含后缀)作为Date列的值
    filename = os.path.basename(full_path).rsplit('.')[0]
    df = pd.read_csv(full_path, sep='|', header=None, names=columns)
    df_dict[filename] = df

# 合并所有DataFrame并添加Date列
merged_df = pd.concat(df_dict, names=['Date']).reset_index(level=0)
# 输出为TSV格式(若需CSV可将sep改为',')
merged_df.to_csv('output_file.tsv', index=False, sep='\t')

关键修正点

  • 用os.path.join(cwd, f)拼接完整文件路径,确保pd.read_csv能定位到正确文件。
  • 添加if f.endswith('.tsv')过滤非TSV文件,避免误读无关文件。
  • 移除冗余的外层循环,仅执行一次合并逻辑。
  • 明确指定sep='\t'输出标准TSV格式,符合文件类型规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:30:52