An example in python of merging two text files and sorting them by first name

  • 2020-04-02 13:36:24
  • OfStack

Some time ago, I saw a section of the exam on the Internet. The requirements are as follows:

The employee file records the job number and name


    cat employee.txt:    
    100 Jason Smith    
    200 John Doe    
    300 Sanjay Gupta    
    400 Ashok Sharma

Record the job number and salary in the bonus file

    cat bonus.txt:    
    100 $5,000    
    200 $500    
    300 $3,000    
    400 $1,250

Required to merge the two files and output the following, processing results:

    400 ashok sharma $1,250    
    100 jason smith  $5,000    
    200 john doe  $500    
    300 sanjay gupta  $3,000

 

This is required to use the shell to write, but my shell foundation is not good, using python to achieve

Notice that you also need to sort the implementation code by first name in the output file, by title


#! /usr/bin/env 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()


Related articles: