python - 如何将两个文本文件合并为一个?
问题描述
我有两个文本文件。我想将他们的一些列合并到一个新的文本文件中。
我正在尝试这个,但它不起作用:
with open('1','r') as first:
with open('2', 'r') as second:
data1 = first.readlines()
for line in data1:
output = [(item.strip(), line.split(' ')[2]) for item in second]
f = open("1+2","w")
f.write("%s %s\n" .format(output))
f.close()
我拥有的第一个文本文件:
1
2
3
4
我拥有的第二个文本文件:
1 3
2 5
5 7
7 3
我想要一个新文件,其中第一个文件中的列和第二个文件中的第二列,如下所示:
1 3
2 5
3 7
4 3
解决方案
您可以遍历相应的行对,并将第一个文件的第一列与第二个文件的第二列连接起来:
with open('file_1.txt') as f1, open('file_2.txt') as f2, open('new_file.txt', 'w') as fr:
for line in ("{} {}".format(l1.rstrip('\n'), l2.split(maxsplit=1)[1]) for l1, l2 in zip(f1, f2)):
fr.write(line)
如果您确定列由单个空格分隔,您还可以使用str.partition
如下:
l2.partition(' ')[-1]
例子:
In [28]: with open('file_1.txt') as f1, open('file_2.txt') as f2, open('new_file.txt', 'w') as fr:
...: for line in ("{} {}".format(l1.rstrip('\n'), l2.split(maxsplit=1)[1]) for l1, l2 in zip(f1, f2)):
...: fr.write(line)
...:
In [29]: cat new_file.txt
1 3
2 5
3 7
4 3
顺便说一句,当您在两个文件中没有相同数量的行,并且您想继续对最长的行进行操作时,您可以查看itertools.zip_longest
而不是zip
.
推荐阅读
- python - 通过模型过滤器获取所有相关对象
- python - 如何格式化字符串类型的 jinja2 日期
- javascript - 没有及时设置状态
- image - 我应该同时使用 no-webp 和 no-jpeg2000 作为 Modernizr 的后备吗?
- nginx - 到tomcat的nginx代理
- single-sign-on - FreshWorks SSO 与 OIDC 中的 AD B2C 集成 - 登录错误
- python - 在 tensorflow 2.0.1 中保存和加载具有自定义层的模型
- php - 如何在larave中合并2个相同的集合
- xamarin - 用户抱怨 Xamarin Android 应用程序冻结
- reactjs - 在我的计时器结束时出现此错误:“无法对未安装的组件执行 React 状态更新。这是一个无操作,但它表明......”