Concatenating at the end of a string - Python -


i have file looks this:

atom coordinatex coordinatey coordinatez atom coordinatex coordinatey coordinatez ... 

i'm trying add atom number (starting 0) file this:

atom0 coordinatex coordinatey coordinatez atom1 coordinatex coordinatey coordinatez ... 

here's code , problem:

readfile = open("coordinates.txt", 'r') writefile = open("coordinatesformatted.txt", 'w') index = 1 counter = 0  linetoread in readfile:     linetoread = linetoread.lstrip()     if index % 2 == 0:         counter = counter + 1         linetoread+=str(counter)      writefile.write(linetoread)     index = index+1  readfile.close() writefile.close()  f = open('coordinatesformatted.txt','r') temp = f.read() f.close()  f = open('coordinatesformatted.txt', 'w') f.write("0") f.write(temp) f.close() 

instead of having desired output after run code this:

0atom coordinatex coordinatey coordinatez 1atom coordinatex coordinatey coordinatez ... 

any appreciated!

you have 2 combined problems makes funny combination: odd/even problem on counter , use of lstrip instead of strip: strip removes linefeed shift lines.

i rewrote code, removing last part useless , works expected.

readfile = open("coordinates.txt", 'r') writefile = open("coordinatesformatted.txt", 'w') index = 1 counter = -1  linetoread in readfile:     linetoread = linetoread.strip()     if index % 2:         counter += 1         linetoread+=str(counter)  # append counter atom without linefeed     writefile.write(linetoread+"\n") # write line, adding linefeed again     index += 1  readfile.close() writefile.close() 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -