python - 将 txt 文件的行与输出连接到另一个 txt 文件。Python
问题描述
我是 Python 新手,我试图将一个 file1.txt 的行与另一个 file2.txt 连接起来,它的输出必须是另一个 file3.txt 例如:
文件 1.txt:
Hello how are u?:
NYC:
Coffee Shop:
文件2.txt:
Jhon
WDC
Starbucks
输出应该是:
文件 3.txt:
Hello how are u?: Jhon
NYC: WDC
Coffe Shop: Starbucks
我有这个:
from io import open
input1=open("file1.txt","r",encoding="utf-8")
input2=open("file2.txt","r",encoding="utf-8")
output=open("file3.txt","w",encoding="utf-8")
file1=input1.readlines()
file2=input2.readlines()
j=0
for i in ingles:
out=file1[j]+":"+file2[j]
j=j+1
output.writelines(out)
input1.close()
input2.close()
output.close()
它创建文件,但不会将结果连接在同一行中......
解决方案
此实现处理不等行长度的文件。
#!/usr/bin/python
from __future__ import print_function
FILE_A = './file1.txt'
FILE_B = './file2.txt'
OUTPUT = './file3.txt'
with open(FILE_A, 'r') as file_a, open(FILE_B, 'r') as file_b:
with open(OUTPUT, 'w') as out:
for a, b in map(None, file_a.readlines(), file_b.readlines()):
a = a.rstrip() if a is not None else ''
b = b.rstrip() if b is not None else ''
print('%s%s' % (a, b), file=out)
用法:
第一个文件的内容$ cat file1.txt
Hello how are u?:
NYC:
Coffee Shop:
foo
第二个文件的内容
$ cat file2.txt
Jhon
WDC
Starbucks
执行脚本
$ python concatenate.py
输出文件的内容
$ cat file3.txt
Hello how are u?:Jhon
NYC:WDC
Coffee Shop:Starbucks
foo
$
推荐阅读
- c++ - 使用 Boost C++ 库
- r - 替换 R 列中的值而不影响具有相同字符的单词
- python - 如何使用已经训练好的模型对记录进行分类?
- javascript - Express.js 中的 req.query 未定义
- python - 针对参数的不同值迭代函数
- linux - 如何创建与 mt 命令一起使用的虚拟磁带设备?
- javascript - 将文本添加到按钮的正确方法是什么?
- excel - 如何在工作簿中跳过打印特定工作表,如果特定单元格值 (D4) 为空白。Vba Excel?
- r - R:循环过滤
- amazon-web-services - 通过堡垒主机到 VPC 中的 Elasticsearch 集群的 ssh 端口转发不起作用