python - 使用 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 文件中。
解决方案
如果需要合并一包类似格式的文件,不需要实际将数据加载到内存中,我们可以直接将所有文件转储到一个。
下面的片段将检查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")
推荐阅读
- python - 在 Spyder python 编辑器中将控制台输出记录到日志文件的 Pythonic 方式
- android - 我们为 Cordova iOS/Android 移动应用程序使用什么 OAuth 2.0 重定向 URI?
- php - 运行 PHP 7.2 的 Vagrant Scotchbox 上的 Xdebug - 配置
- ruby-on-rails - 了解 Rails 多态关联
- c# - 不要发布 sqlproj
- scala - 如何使用 Stream 正确调用方法?
- ssl - Coldfusion CFHTTP SSL 无客户端证书
- html - 为什么我的段落总是溢出div
- arrays - 如何将元素数组转换为 Scala 中可变元素方法的单个元素?
- css - iPhone X“下巴”导致 Cordova 应用程序无法利用空间