Python sample code for merging text files,

Source: Internet
Author: User

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 ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.