python中合并两个文本文件并按照姓名首字母排序的例子
时间:2023-05-28 17:41:32
前段时间前在网上看到一段面试题,要求如下:
employee文件中记录了工号和姓名
cat employee.txt:
100 Jason Smith
200 John Doe
300 Sanjay Gupta
400 Ashok Sharma
bonus文件中记录工号和工资
cat bonus.txt:
100 $5,000
200 $500
300 $3,000
400 $1,250
要求把两个文件合并并输出如下, 处理结果:
400 ashok sharma $1,250
100 jason smith $5,000
200 john doe $500
300 sanjay gupta $3,000
这个是要求用shell来写的,但我的shell功底不怎么样,就用python来实现了
注意,按题目的意思,在输出文件中还需要按照姓名首字母来排序的,实现代码
#! /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()
标签:python,合并文件,字母排序
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
解析MySQL数据库性能优化的六大技巧
2024-01-13 02:18:49
使用Python监控文件内容变化代码实例
2021-06-05 22:45:19
仿vue-cli搭建属于自己的脚手架的方法步骤
2024-05-21 10:18:09
Python封装shell命令实例分析
2022-03-11 13:39:37
django实现类似触发器的功能
2023-10-10 22:36:41
![](https://img.aspxhome.com/file/2023/7/99407_0s.jpg)
教你如何在pycharm中使用less
2021-08-12 13:59:32
![](https://img.aspxhome.com/file/2023/9/102739_0s.png)
mysql下mysqladmin日常管理命令总结(必看篇)
2024-01-16 23:35:55
浅谈Oracle数据库的建模与设计
2010-07-20 12:55:00
分析Python编程时利用wxPython来支持多线程的方法
2021-03-09 12:02:57
网页编辑常用表现的实现方法
2010-07-02 16:24:00
pycharm配置python 设置pip安装源为豆瓣源
2022-07-16 12:09:43
![](https://img.aspxhome.com/file/2023/0/86250_0s.png)
JavaScript Reduce使用详解
2024-04-19 10:16:03
![](https://img.aspxhome.com/file/2023/0/135870_0s.jpg)
python基于Tkinter实现人员管理系统
2021-05-01 10:07:19
![](https://img.aspxhome.com/file/2023/5/128765_0s.jpg)
如何使用Python的Requests包实现模拟登陆
2022-10-07 03:12:26
![](https://img.aspxhome.com/file/2023/3/75123_0s.png)
vue组件间传值的方法你知道几种
2024-04-28 09:31:32
Bootstrap中文本框的宽度变窄并且加入一副验证码图片的实现方法
2024-04-16 08:48:57
![](https://img.aspxhome.com/file/2023/3/137013_0s.png)
python 算法题——快乐数的多种解法
2021-12-25 06:32:43
css学习笔记:为什么在IE6下图片会往下掉一行
2009-06-19 12:50:00
![](https://img.aspxhome.com/file/UploadPic/20099/25/2009925225543206s.jpg)
pycharm将英文设置为中文的详细教程
2022-07-16 14:22:24
![](https://img.aspxhome.com/file/2023/0/127110_0s.png)
kali最新国内更新源sources
2022-03-25 02:53:37
![](https://img.aspxhome.com/file/2023/7/99367_0s.png)