【发布时间】:2016-10-21 20:26:44
【问题描述】:
我想合并两个文件。代码应将两个文件(input1.txt 和 input2.txt)的第二行相加,将求和的结果写入文件(final.txt),将 input2.txt 中以“1MOL”开头的所有行追加到final.txt,最后将 input1.txt 中的所有行(前两行除外)附加到 final.txt 中。我的代码只将“18”(两个输入文件中第二行的总和)写入 final.txt。如何修复我的代码?
input1.txt
Molecule in solvent
13
1MET N 1 4.761 6.470 2.128
1MET H1 2 4.749 6.567 2.153
1MET H2 3 4.833 6.430 2.184
1MET H3 4 4.785 6.464 2.031
1MET CA 5 4.636 6.399 2.152
1MET HA 6 4.567 6.442 2.093
1MET CB 7 4.651 6.250 2.113
1MET HB1 8 4.730 6.213 2.162
1MET HB2 9 4.667 6.244 2.015
1MET CG 10 4.530 6.163 2.147
1MET HG1 11 4.452 6.219 2.119
1MET HG2 12 4.532 6.156 2.247
1MET SD 13 4.524 5.998 2.070
spc.itp
input2.txt:
Gallium Rubidium
5
1MOL CL 1 2.131 2.473 6.188
1MOL P 2 1.714 2.422 6.273
1MOL O 3 1.839 2.324 6.306
1MOL O 4 1.783 2.542 6.188
1MOL O 5 1.682 2.491 6.416
我的代码:
search_string = 'MOL'
#read the first input file
with open("input1.txt", mode="r") as f1:
#open a file to merge two files
with open("final.txt", mode="a") as f:
#skip the first line of the input1.txt
line=f1.readlines()
#take the second line of input1.txt
a=float(line[1])
#read the second input file
with open("input2.txt", mode="r") as f2:
f2lines=f2.readlines()
b=float(f2lines[1])
result=float(a+b)
f.write("%.f\n" % result)
for f2lines in f2:
if search_string in f2lines:
f.write(f2lines)
所需的 final.txt:
18
1MOL CL 1 2.131 2.473 6.188
1MOL P 2 1.714 2.422 6.273
1MOL O 3 1.839 2.324 6.306
1MOL O 4 1.783 2.542 6.188
1MOL O 5 1.682 2.491 6.416
1MET N 1 4.761 6.470 2.128
1MET H1 2 4.749 6.567 2.153
1MET H2 3 4.833 6.430 2.184
1MET H3 4 4.785 6.464 2.031
1MET CA 5 4.636 6.399 2.152
1MET HA 6 4.567 6.442 2.093
1MET CB 7 4.651 6.250 2.113
1MET HB1 8 4.730 6.213 2.162
1MET HB2 9 4.667 6.244 2.015
1MET CG 10 4.530 6.163 2.147
1MET HG1 11 4.452 6.219 2.119
1MET HG2 12 4.532 6.156 2.247
1MET SD 13 4.524 5.998 2.070
spc.itp
【问题讨论】:
-
我强烈建议您使用 pandas 数据框进行此操作。 pandas.pydata.org/pandas-docs/stable/merging.html
标签: python