python代码中两个数据文件的合并和求和的问题

时间:2019-05-20 18:11:03

标签: python

我在python中有两个代码,其中一个假设是合并两个文件,另一个则必须对两个文件的行求和。但是它们两个都只用一行产生输出文件,而输入文件则由8行组成。 这是合并output.txtmass.txt两个文件的第一个代码:

outfile = open("output.txt", "r")
massfile = open("mass.txt", "r")
finaloutfile = open("final_output.txt", "w")
for line in outfile:
    finaloutfile.write(massfile.readline().rstrip("\n")+" "+line)

outfile.close()
massfile.close()
finaloutfile.close()

第二个代码用于添加两个文件output.txtearth.txt的行:

outfile = open("output.txt", "r")
earthfile = open("earth.txt", "r")
earthoutfile = open("earth_output.txt", "w")
for line in outfile:
    sl = line.split()
    lsl = len(sl)
    msl = earthfile.readline().split()
    idxmsl = 0

    for i in range(lsl-1):
        earthoutfile.write(str(float(sl[i])+float(msl[i]))+" ")
    earthoutfile.write(str(float(sl[lsl-1])+float(msl[lsl-1]))+"\n")

outfile.close()
earthfile.close()
earthoutfile.close()

出什么问题了?为什么它们不合并,添加或添加输入文件行?

1 个答案:

答案 0 :(得分:0)

关于两个文件的合并,我会这样写:

outfile = open("output.txt", "r")
massfile = open("mass.txt", "r")
with open("final_output.txt", "a") as finaloutfile:
    outlines = outfile.readlines()
    masslines = massfile.readlines()
    for line in outlines:
        finaloutfile.write(line)
    for line in masslines:
        finaloutfile.write(line)

outfile.close()
massfile.close()

我刚刚对其进行了测试,并且可以正常工作。