我愿意在线连接两个文件,这样每个文件的每一行都被连续地合并到第三个文件中。
因此,我有以下代码和以下文本文件:
file1.txt
1
3
5
7
file2.txt
2
4
6代码:
from ast import literal_eval
def merge_lines():
with open("file1.txt") as f1, open("file2.txt") as f2:
with open("file3.txt", "r+") as tfile:
f1_lists = (literal_eval(line) for line in f1)
f2_lists = (literal_eval(line) for line in f2)
for l1, l2 in zip(f1_lists, f2_lists):
tfile.write(str(l1))
tfile.write("\n")
tfile.write(str(l2))
tfile.write("\n")
combine_hands()这很好,因为输出文件看起来是这样的:
file3.txt
1
2
3
4
5
6我的问题是为什么没有合并文件1.txt的最后一行(第7行)?
发布于 2018-09-17 05:29:12
最后一行被省略了,因为zip停止在较短的可迭代性的末尾。
你想要的可能是
from itertools import zip_longest
def merge_lines():
with open("file1.txt") as f1,\
open("file2.txt") as f2,\
open("file3.txt", "w") as tfile:
for l1, l2 in zip_longest(f1, f2, fillvalue="Empty line"):
# Or you can place a sentinel value for `fillvalue`
# and check it and don't write to file when you see it.
tfile.write(l1.strip() + "\n")
tfile.write(l2.strip() + "\n")或者如果您不想写出来来归档空行
for l1, l2 in zip_longest(f1, f2, fillvalue=None):
if l1:
tfile.write(l1)
if l2:
tfile.write(l2)由于fillvalue的默认值是None,我们可以将其进一步简化为
for l1, l2 in zip_longest(f1, f2):
if l1:
tfile.write(l1)
if l2:
tfile.write(l2)编辑
在阅读了@DYZ的评论和答复后,做了以下更改:
发布于 2018-09-17 05:37:16
使用函数zip_longest,您的代码可以以非常紧凑的方式编写:
from itertools import zip_longest
with open("file1.txt") as f1,\
open("file2.txt") as f2,\
open("file3.txt", "w") as tfile:
for l1, l2 in zip_longest(f1, f2, fillvalue=''):
if l1 != '': tfile.write(l1)
if l2 != '': tfile.write(l2)不需要显式读取或类型转换。
发布于 2018-09-17 06:08:47
正如其他人所提到的,这是因为您使用了普通zip(),得到omitted.zip的最长列表(文件)的最后一行将形成元组,直到短列表的长度
相反,您可以使用下面的任何一个扩展zip,它将显示到最长的列表
itertools.zip_longest -- in python 3.x +
itertools.izip_longest --in python 2.6+https://stackoverflow.com/questions/52361198
复制相似问题