Skip to content Skip to sidebar Skip to footer

How To Interate Over N Lines Of A Text File In Python

Hello I'm trying to convert the file disp.txt from: 116 C 0.12 -0.91 0.39 -0.40 0.31 0.85 -0.66 -0.18 -0.22 117 O 0.00 -0.02 0.00 -0.05 0.0

Solution 1:

Here's a way to do it:

withopen('disp.txt') as f, open('disp.mol','w') asout:
    vibration = 1for line in f:
        line1 = line.split()
        line2 = next(f).split() # also get next linefor i inrange(2,len(line1),3):
            out.write('vibration {}\n'.format(vibration))
            out.write(' '.join(line1[i:i+3])+'\n')
            out.write(' '.join(line2[i:i+3])+'\n')
            vibration += 1

Output:

vibration 1
0.12 -0.91 0.39
0.00 -0.02 0.00
vibration 2
-0.40 0.31 0.85-0.05 0.05 0.12
vibration 3
-0.66 -0.18 -0.22-0.57 -0.26 -0.29
vibration 4
-0.03 -0.04 0.00-0.14 0.88 -0.45
vibration 5
0.01 0.09 0.19
0.47 -0.33 -0.79
vibration 6
-0.71 -0.21 -0.26
0.57 0.16 0.19

Post a Comment for "How To Interate Over N Lines Of A Text File In Python"