2017-07-31 65 views
0

我有兩個txt文件。我想用python合併這些文件。 我剛開始學習python,需要一些幫助。我試圖搜索谷歌解決這個問題,但我找不到解決方案。如何使用python txt文件合併?

所以請幫助我。

下面是我的兩個txt文件。

a.txt有此數據。

Zone,alias1,alias2 
PA1_H1,PA1,H1 
PA2_H2,PA2,H2 

b.txt有此數據。

WWN,Port,Aliases 
da,0,PA1 
dq,1,PA2 
d2,3,H1 
d4,1,H2 

期望輸出

Zone,alias1,WWN,Port,alias2,WWN,Port 
PA1_H1,PA1,da,0,H1,d2,3 
PA2_H2,PA2,dq,1,H2,d4,1 

我想下面的腳本,但我不能合併。

row = [] 
for line in open("mod_alias.txt"): 
     line = line.split(',')[2] 
     row.append(line) 

strings = row 

for line in open("mod_all_cfgshow.txt"): 
     if any(s in line for s in strings): 
       field1,field2,field3 = line.split(',') 
       print field1,field2,field3 

如何合併文件? 你能告訴我一個例子嗎?

+1

合併的標準是什麼?基於哪一列? –

回答

0

這應該讓你開始

import csv 

# read all the data in b.txt into a dictionary, key'd by the alias. We'll look this up later 
data = {} 
with open("b.txt") as infile: 
    for row in csv.DictReader(infile): 
     alias = row["Aliases"] 
     data[alias] = row 

with open("a.txt") as fin, open("output.txt", 'w') as fout: 
    infile = csv.DictReader(fin) 
    outfile = csv.DictWriter(headers=infile.headers+data.keys()) 
    for row in infile: 
     row.update(data[row["Aliases"]]) # update the row with the data from b.txt 
     outfile.writerow(row) 
+0

非常感謝。但是你的腳本有錯誤。 'Traceback(last recent call last): 文件「test7.py」,第12行,在 outfile = csv.DictWriter(headers = infile.headers + data.keys()) AttributeError:DictReader實例沒有屬性'標題' ' – KJ9

0

下面是一些代碼,讓你開始。此代碼將向您展示如何打開這兩個文件並將其合併。然後,您需要做的就是修改代碼,以使用您希望的任何特定規則合併文件。

# Open Files, read data to lists, and strip data 

    with open("b.txt") as bFile: 
      bContent = bFile.readlines() 
      bContent = [line.strip() for line in bContent] 


    with open('a.txt') as aFile: 
      aContent = aFile.readlines() 
      aContent = [line.strip() for line in aContent] 

    # Create a file to store the merged text 

    m = open('merged.txt','w') 

    # Cycle through the text read from files and merge, and then print to file 
    for aLine, bLine in zip(aContent, bContent): 

      mergedString = aLine+','+bLine 
      print>>m,mergedString 
相關問題