Python sample code for merging text files,
Python merge text file sample code.
Python combines two texts
Employee ID and name are recorded in the employee file
Cat employee.txt:
100 Jason Smith
200 John Doe
300 Sanjay Gupta
400 Ashok Sharma
Bonus file records employee ID and salary
Cat bonus.txt:
100 $5,000
200 $500
300 $3,000
400 $1,250
Merge the two files and output the following results:
400 ashok sharma $1,250
100 jason smith $5,000
200 john doe $500
300 sanjay gupta $3,000
This should be written using shell, but I have little knowledge about shell, so I can use python to implement it.
Note: According to the question, the output file must also be sorted by the first letter of the name.
#! /Usr/bin/env python # coding = utf-8fp01 = open ("bonus.txt", "r") a = [] for line01 in fp01:. 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" % (line02.split () [0], line02.split () [1], line02.split () [2], a [I]. split () [1]) fp01.close () fp02.close ()