如何在python中将两个文件的输出组合成单个?

时间:2015-05-19 19:20:21

标签: python file python-2.7

我的代码如下所示: 现在我的代码分别输出两个名为absorbance.txt和energy.txt的文本文件。我需要修改它,以便它只输出一个名为combined.txt的文件,使得combined.txt的每一行都有两个以逗号分隔的值。第一个值必须来自absorbance.txt,第二个值必须来自energy.txt。 (如果有人对我的写作感到困惑,我表示歉意,如果您需要更多澄清,请发表评论)

g = open("absorbance.txt", "w")
h = open("Energy.txt", "w")

ask = easygui.fileopenbox()
f = open( ask, "r")
a = f.readlines()
bg = []
wavelength = []
for string in a:

    index_j = 0
    comma_count = 0
    for j in string:
        index_j += 1

        if j == ',':
            comma_count += 1
            if comma_count == 1:

                slicing_point = index_j
                t = string[slicing_point:]
                new_str = string[:(slicing_point- 1)]
                new_energ = (float(1239.842 / int (float(new_str))) * 8065.54)
                print >>h, new_energ


import math
list = []
for i in range(len(ref)):


    try:
        ans = ((float (ref[i]) - float (bg[i])) / (float(sample[i]) - float(bg[i])))
        print ans
        base= 10  
        final_ans =  (math.log(ans, base))
    except:
        ans = -1 * ((float (ref[i]) - float (bg[i])) / (float(sample[i]) - float(bg[i])))
        print ans
        base= 10  
        final_ans =  (math.log(ans, base))

    print >>g, final_ans

2 个答案:

答案 0 :(得分:1)

与罗伯特的方法类似,但旨在尽可能简化控制流程。

absorbance.txt:

Hello
How are you
I am fine
Does anybody want a peanut?

energy.txt:

123
456
789

代码:

input_a = open("absorbance.txt")
input_b = open("energy.txt")
output = open("combined.txt", "w")
for left, right in zip(input_a, input_b):
    #use rstrip to remove the newline character from the left string
    output.write(left.rstrip() + ", " + right)

input_a.close()
input_b.close()
output.close()

combined.txt:

Hello, 123
How are you, 456
I am fine, 789

请注意,absorbth.txt的第四行未包含在结果中,因为energy.txt没有第四行。

答案 1 :(得分:0)

您可以打开两个文本文件并将它们附加到新文本文件,如下所示。这是我根据您的问题给出的,不一定是您提供的代码。

combined = open("Combined.txt","w")    
with open(r'Engery.txt', "rU") as EnergyLine:
    with open(r'Absorbance.txt', "rU") as AbsorbanceLine:
        for line in EnergyLine:
            Eng = line[:-1]
            for line2 in AbsorbanceLine:
                Abs = line2[:-1]
                combined.write("%s,%s\n" %(Eng,Abs))
                break
combined.close()