我在python中有两个代码,其中一个假设是合并两个文件,另一个则必须对两个文件的行求和。但是它们两个都只用一行产生输出文件,而输入文件则由8行组成。
这是合并output.txt
和mass.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.txt
和earth.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()
出什么问题了?为什么它们不合并,添加或添加输入文件行?
答案 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()
我刚刚对其进行了测试,并且可以正常工作。