用python实现两个文本合并
一段时间前在网上看到一段面试题,要求如下:
employee文件中记录了工号和姓名
cat employee.txt:
100 Jason Smith
200 John Doe
300 Sanjay Gupta
400 Ashok Sharma
bonus文件中记录工号和工资
cat bonus.txt:
100 $5,000
200 $500
300 $3,000
400 $1,250
要求把两个文件合并并输出如下, 处理结果:
400 ashok sharma $1,250
100 jason smith $5,000
200 john doe $500
300 sanjay gupta $3,000
这个应该是要求用shell来写的,但我的shell功底不怎么样,就用python来实现了
注意,按题目的意思,在输出文件中还需要按照姓名首字母来排序的
1 #! /usr/bin/env python 2 #coding=utf-8 3 fp01 = open("bonus.txt", "r") 4 a = [] 5 for line01 in fp01: 6 a.append(line01) 7 8 fp02 = open("employee.txt", "r") 9 10 fc02 = sorted(fp02, key = lambda x:x.split()[1]) 11 12 for line02 in fc02: 13 i = 0 14 while line02.split()[0]!=a[i].split()[0]: 15 i += 1 16 print "%s %s %s %s" % (line02.split()[0], line02.split()[1], line02.split()[2], a[i].split()[1]) 17 18 fp01.close() 19 fp02.close()
本文是原创内容,欢迎转载,但请注明出处!
http://www.cnblogs.com/cjyfff/