python實現兩個文本合並
employee文件中記錄了工號和姓名
100 Jason Smith
200 John Doe
300 Sanjay Gupta
400 Ashok Sharma
bonus文件中記錄工號和工資
100 $5,000
200 $500
300 $3,000
400 $1,250
要求把兩個文件合並並輸出如下, 處理結果:
100 jason smith $5,000
200 john doe $500
300 sanjay gupta $3,000
這個應該是要求用shell來寫的,但我的shell功底不怎麼樣,就用python來實現了
注意,按題目的意思,在輸出文件中還需要按照姓名首字母來排序的
#coding=utf-8
fp01=open("bonus.txt","r")
a=[]
for line01 in fp01:
a.append(line01)
fp02=open("employee.txt","r")
fc02=sorted(fp02,key=lambda x:x.split()[1])
for line02 in fc02:
i=0
while line02.split()[0]!=a[i].split()[0]:
i+=1
print "%s %s %s %s" % (line02.split()[0],line02.split()[1],line02.split()[2],a[i].split()[1])
fp01.close()
fp02.close()
參考自:http://www.jbxue.com/article/11082.html