Ich möchte zwei Dateien zusammenführen. Der Code sollte die zweite Zeile beider Dateien summieren (input1.txt und input2.txt), in eine Datei (final.txt) das Ergebnis dieser Summierung schreiben, alle Zeilen beginnend mit "1MOL" in der input2.txt anhängen final.txt und schließlich alle Zeilen (außer den ersten beiden Zeilen) in der Datei input1.txt an die final.txt anhängen. Mein Code schreibt nur "18" (die Summe der zweiten Zeilen in beiden Eingabedateien) in die final.txt. Wie kann ich meinen Code reparieren?wie zwei Dateien mit Python zusammengeführt werden
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
Mein Code:
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)
Wunsch 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
Ich würde Ihnen empfehlen, Pandas Datenrahmen für diese Operationen zu verwenden. http://pandas.pydata.org/pandas-docs/stable/merging.html – Nf4r