如何利用python合并文本
这篇文章主要介绍了python合并文本文件示例,需要的朋友可以参考下
python实现两个文本合并
employee文件中记录了工号和姓名
cat employee.txt:100 Jason Smith200 John Doe300 Sanjay Gupta400 Ashok Sharma
bonus文件中记录工号和工资
cat bonus.txt:100 $5,000200 $500300 $3,000400 $1,250
要求把两个文件合并并输出如下, 处理结果:
立即学习“Python免费学习笔记(深入)”;
400 ashok sharma $1,250100 jason smith $5,000200 john doe $500300 sanjay gupta $3,000
这个应该是要求用shell来写的,但我的shell功底不怎么样,就用python来实现了
注意,按题目的意思,在输出文件中还需要按照姓名首字母来排序的
#! /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],line02.split()[1],line02.split()[2],a[i].split()[1])fp01.close()fp02.close()