Dear All,
I am writing a script to split a file into several files. The structure of the sample file is like follows,
9 # the number of atoms
i = 0 # the number of step
N X_00 Y_00 Z_00 # from this line to the followed 9 lines are the coordinates of each atom
H X_01 Y_01 Z_01
H X_02 Y_02 Z_02
H X_03 Y_03 Z_03
H X_04 Y_04 Z_04
N X_05 Y_05 Z_05
H X_06 Y_06 Z_06
H X_07 Y_07 Z_07
H X_08 Y_08 Z_08
9
i = 1
N X_10 Y_10 Z_10
H X_11 Y_11 Z_11
H X_12 Y_12 Z_12
H X_13 Y_13 Z_13
H X_14 Y_14 Z_14
N X_15 Y_15 Z_15
H X_16 Y_16 Z_16
H X_17 Y_17 Z_17
H X_18 Y_18 Z_18
9
i = 2
N X_20 Y_20 Z_20
H X_21 Y_21 Z_21
H X_22 Y_22 Z_22
H X_23 Y_23 Z_23
H X_24 Y_24 Z_24
N X_25 Y_25 Z_25
H X_26 Y_26 Z_26
H X_27 Y_27 Z_27
H X_28 Y_28 Z_28
...... repeat the blocks but the different coordinates.
The aim is to split the coordinates by each atoms and save them into 9 files according to atoms(lines). For example, the first file contains the coordinates of the first atom (the coordinates of the first line), the second file contains the coordinates of the second atom (the second line), and so forth.
file0 # save the coordinates of the first lines of each step
X_00 Y_00 Z_00
X_10 Y_10 Z_10
X_20 Y_20 Z_20
……
file1 # save the coordinates of the second lines of each step
X_01 Y_01 Z_01
X_11 Y_11 Z_11
X_21 Y_21 Z_21
......
file2 # save the coordinates of the third lines of each step
X_02 Y_02 Z_02
X_12 Y_12 Z_12
X_22 Y_22 Z_22
......
I have finished my script and it worked except for missing the last iteration. For instance, there 10 steps in the sample file. As a result, each output files should have 10 lines of coordinates. However, in my results, only 9 lines of coordinates in each file.
My script is shown as follows,
#!/usr/bin/python
Natom = int(fo.next())
line = fo.next()
timestep = 0
coords = []
row = 0
for line in fo:
try:
if row < Natom:
info = line.split()
coords.append(info[1:])
row += 1
else:
for n in range(Natom):
with open('position%d.txt' %n, 'a+') as fw:
xyz = coords[n]
output = "%s, %s, %s" %(xyz[0], xyz[1], xyz[2])
fw.write(output + "\n")
coords = []
row = 0
timestep += 1
line = fo.next()
except StopIteration:
break
Enclosed please find the sample file (
sample.xyz) and my script (split_test.py). Any suggestion would be greatly appreciated.
Regards,
Huan