【问题标题】:Merge multiple text files as one CSV file将多个文本文件合并为一个 CSV 文件
【发布时间】:2017-08-17 10:57:43
【问题描述】:
我有几个文件包含这样的数据:
file1.txt
abc
def
hij
file2.txt
def
abc
qlm
file3.txt
def
lop
tmn
想要的输出:
合并文件.csv
file1 file2 file2
abc def def
def abc lop
hij qlm tmn
【问题讨论】:
标签:
python
python-2.7
csv
merge
【解决方案1】:
Python 文档CSV File Reading and Writing
例如,最低内存占用:
import io, csv
fieldnames = [file1, file2, file3]
with io.open(csv_file, 'w', newline='') as fh_csv, \
open(file1) as fh1, \
open(file2) as fh2, \
open(file3) as fh3:
writer = csv.writer(fh_csv, delimiter='\t')
writer.writerow(fieldnames)
while True:
out = []
for fh in [fh1, fh2, fh3]:
out.append( fh.readline().strip('\n') )
if all(out):
writer.writerow(out)
else:
break
输出:
file1.txt file2.txt file3.txt
abc def def
def abc lop
hij qlm tmn
用 Python:3.4.2 测试
【解决方案2】:
你应该尝试自己写一些代码:
我的方式:
file_list=['a','b','c']
open("o","w").write("\n".join([" ".join(i).replace("\n","") for i in list(zip(*[list(open(i)) for i in file_list]))]))
结果:
file1.txt file2.txt file3.txt
abc def def
def abc lop
hij qlm tmn
我读取了这三个文件并将数据附加到三个列表中,然后使用zip 来聚合元素。如果您想与Python2.x 和Python3.x 兼容,可以将其添加到代码的顶部:
try:
from itertools import izip as zip
except ImportError:
pass
然后我删除\n 字符,并组合列表并将它们写入文件。
【解决方案3】:
我的方式:
import pandas as pd
df1=pd.read_csv('file1.txt',names=['file1'])
df2=pd.read_csv('file2.txt',names=['file2'])
df3=pd.read_csv('file3.txt',names=['file3'])
result=pd.concat([df1,df2,df3],axis=1)
result.to_csv('mergedfile.txt',index=False)
或更多python风格:
import os
import pandas as pd
def merge_files(file_list, export_file):
df_list = [pd.read_csv(
one_file, names = [os.path.splitext(os.path.basename(one_file))[0]]
) for one_file in file_list if os.path.isfile(one_file)]
all_df=pd.concat(df_list,axis=1)
all_df.to_csv(export_file, index=False)
if __name__=='__main__':
sample_files=['./file1.txt', '../temp/file2.txt','file3.txt']
merge_files(sample_files,"mergedfile.txt")