[英]Python side-by-side merge of comma-delimited text files
假設我有兩個文本文件,其內容如下所示。
文字檔1:
Apple, 0
Pear, 1
Orange, 0
文字檔2:
Apple, 1
Pear, 1
Orange, 1
我希望以並排方式合並它們,只保留文本文件1的左“列”,這對兩個文本文件都是相同的。也就是說,我希望生成以下合並的文本文件。
合並的文本文件:
Apple, 0, 1
Pear, 1, 1
Orange, 0, 1
我試圖找到如何-用少量的代碼-執行這種合並。 但是,在實際問題中,可以有任意數量的文本文件。 如何在Python中執行此操作?
假設:
我想zip
,然后通過他們在同一時間走。 做一些分割和格式化,然后逐行寫出到新文件中
with open('text1.csv') as f1, open('text2.csv') as f2, open('merge.csv', 'w') as fOut:
for line1, line2 in zip(f1, f2):
name, val1 = line1.strip().split(',')
val2 = line2.strip().split(',')[1]
fOut.write('{}, {}, {}\n'.format(name, val1, val2))
fileinput.input將獲取文件列表,使用ordereddict連接所有值並保持順序:
from collections import OrderedDict
d= OrderedDict()
import fileinput
with open("joined.txt","w") as f:
for line in fileinput.input(["file1.txt","file2.txt","file3.txt","file4.txt"]):
spl = line.strip().split(",")
d.setdefault(spl[0],[])
d[spl[0]] += spl[1:]
for k,v in d.items():
f.write("{} {}\n".format(k,",".join(v)))
如果它們都在自己的目錄中,則可以將os.listdir傳遞給fileinput:
from collections import OrderedDict
d= OrderedDict()
import fileinput
import os
with open("joined.txt","w") as f:
for line in fileinput.input(os.listdir("path_to")):
spl = line.strip().split(",")
d.setdefault(spl[0],[])
d[spl[0]] += spl[1:]
for k,v in d.items():
f.write("{} {}\n".format(k,",".join(v)))
如果它們不是唯一的文件,但遵循某種模式,則可以使用glob:
import fileinput
import os
import glob
with open("joined.txt","w") as f:
for line in fileinput.input(glob.glob("./file*.txt")):
spl = line.strip().split(",")
d.setdefault(spl[0],[])
d[spl[0]] += spl[1:]
for k,v in d.items():
f.write("{} {}\n".format(k,",".join(v)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.