How to combine text with Python

Source: Internet
Author: User
This article mainly describes the python merge text file example, the need for friends can refer to the following

Python implements two text merges

Work number and name are recorded in the employee file

Cat employee.txt:100 Jason Smith200 John Doe300 Sanjay Gupta400 Ashok Sharma

Record work number and salary in bonus file

Cat bonus.txt:100 $5,000200 $500300 $3,000400 $1,250

Request to merge two files and output as follows, processing the result:

Ashok Sharma $1,250100 Jason Smith  $5,000200 John Doe  $500300 Sanjay Gupta  $3,000

This is supposed to be written by the shell, but my shell is not very good, I use Python to achieve

Note that, according to the title, the output file also needs to be sorted by initials.

#!/usr/bin/env python#coding=utf-8fp01=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],line0 2.split () [1],line02.split () [2],a[i].split () [1]) Fp01.close () fp02.close () 

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.