鱼C论坛

 找回密码
 立即注册
查看: 1103|回复: 2

[已解决]脚本合并文件求助

[复制链接]
发表于 2020-1-8 16:56:13 | 显示全部楼层 |阅读模式
20鱼币

有两个文件1.txt和2.txt
1.txt
a
c
e
f
h
......

2.txt
a        112121
b        2342435
c        53465454
d        354365546
e        4235446
f        3543656
g        32435465
h        433456756786
......
生成c.txt
a        112121
c        53465454
e        4235446
f        3543656
h        433456756786
......
最佳答案
2020-1-8 16:56:14
  1. headers = []
  2. result = []

  3. with open('1.txt', 'rt') as flag:
  4.     for line in flag:
  5.         headers.append(line.strip())

  6. with open('2.txt', 'rt') as content:
  7.     for line in content:
  8.         biaozi, neirong = line.split(sep=' ', maxsplit=1)
  9.         if biaozi in headers:
  10.             result.append(line)

  11. with open('c.txt', 'wt') as target:
  12.     for line in result:
  13.         target.write(line)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-1-8 16:56:14 | 显示全部楼层    本楼为最佳答案   
  1. headers = []
  2. result = []

  3. with open('1.txt', 'rt') as flag:
  4.     for line in flag:
  5.         headers.append(line.strip())

  6. with open('2.txt', 'rt') as content:
  7.     for line in content:
  8.         biaozi, neirong = line.split(sep=' ', maxsplit=1)
  9.         if biaozi in headers:
  10.             result.append(line)

  11. with open('c.txt', 'wt') as target:
  12.     for line in result:
  13.         target.write(line)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-1-9 09:52:46 | 显示全部楼层
2#楼正解
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-7 19:37

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表