如何将一个文件中的行附加到另一个文件中的相同行号?

时间:2016-03-29 20:17:12

标签: python python-2.7 python-3.x

file3 = open("over_speeding.txt", "r")
file5 = open("fine.txt", "r")
file6 = open("all details.txt", "a")
x, y = file3.readlines(), file5.readlines()
if file6 == file6.close(): #this just an argument to get the if loop going
     print("not working")

else:
     num = 0 # the of the file that will be appended
     file6.write(y[num] + x[num])
     num += 1

file3.close()
file5.close()
file6.close()
file6 = open("all details.txt", "r")
file66 = file6.read()
print(file66)

这里我试图将两个4行文件合并到一个新文件中,例如file5的第一行附加了file3中的第一行,依此类推。

在if循环我想检查天气文件6是否打开,这不起作用,你能告诉我另一个我可以使用的参数。我试图在没有循环的帮助下输出到文件中,但效率非常低,输出的格式很难改变。

在else循环中如果文件未关闭,则file3和file5行中的信息将根据变量num whih增加1附加,如果num = 4则将停止,我还没有为它编写代码因为我不知道怎么做。

shell中输出的错误是:

file6.write(y[num] + x[num])
ValueError: I/O operation on closed file.

你可以修复这个错误吗?如果可能的话,请告诉我如何在这个上使用for或while循环而不是if循环

1 个答案:

答案 0 :(得分:2)

这样做:

from itertools import zip_longest # izip_longest in Python2

with open("over_speeding.txt") as speeding, open("fine.txt") as fine, open("all details.txt", "a") as everything:
    for speedline, fineline in zip_longest(speeding, fine, fillvalue=""):
        everything.write(speedline.strip() + fineline.strip() + "\n")
相关问题