首页 > 解决方案 > 使用 Python 将具有相同文件名模式(但实际文件名不同)的多个 TSV 文件转换为 CSV

问题描述

一个文件夹中有多个 tsv 文件。我想将每个 tsv 文件转换为 csv 文件,并将所有 csv 文件合并为一个巨型 csv 文件。

customer_data = r"C:\Users\username\Desktop\folder\CustomerData_20201030031520.tsv"
customer_data = pd.read_csv(customer_data,  sep='\t', low_memory=False)

这就是我读取和写入 csv 文件的方式。如何有效地为多个 tsv 文件执行此操作,而不是手动重复此操作?

注意文件名模式?所有文件都将采用这种模式:

CustomerData_"year""month""day_number""random_digits".tsv

我的目标是将所有这些多个 CSV 合并到一个大型 CSV 文件中。

标签: pythoncsv

解决方案


如果需要合并一包类似格式的文件,不需要实际将数据加载到内存中,我们可以直接将所有文件转储到一个。

下面的片段将检查path模式的目录pattern并按文件名对结果列表进行排序。之后,排序顺序的列表将写入out_file文件。

outfile.write("\n")需要的是 *.tsv 文件没有以空行结尾,否则应该注释掉。

import os
import re

path = "c:\\temp\\1"
out_file = "c:\\temp\\1\\big_file.tsv"
pattern = re.compile("^.*_(\d{4})(\d{2})(\d{2})\d{1,10}.\w{3}$")

matched_files = []

for f in os.listdir(path):
  if os.path.isdir(os.path.join(path, f)):
    continue

  if not pattern.match(f):
    continue

  matched_files.append(f)

matched_files = sorted(matched_files)

with open(out_file, "w+") as outfile:
  for f in matched_files:
    with open(os.path.join(path, f), "r") as infile:
      outfile.writelines(infile.readlines())

    outfile.write("\n")

推荐阅读