Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split .txt file rows in Python

I have .txt file as :

x1 x2 x3 y1 y2 y3 z1 z2 z3
x1 x2 x3 y1 y2 y3 z1 z2 z3

For example :

   1.9849207e-01   1.9993099e-01   2.0150793e-01   9.6169322e-02   9.6354487e-02   1.0630896e-01   1.5000000e-02   1.6090730e-02   1.5000000e-02
   1.9993099e-01   2.0261176e-01   2.0150793e-01   9.6354487e-02   1.0536750e-01   1.0630896e-01   1.6090730e-02   1.6090730e-02   1.5000000e-02

I used the following snip :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from itertools import *

with open('path/snip.txt', 'r') as f_input, open('path/snip_output.txt', 'w') as f_output:
    values = []
    for line in f_input:
        values.extend(line.split())

    ivalues = iter(values)

    for triple in iter(lambda: list(islice(ivalues, 3)), []):
        f_output.write(' '.join(triple) + '\n')

and got :

x1 x2 x3
y1 y2 y3
z1 z2 z3
x1 x2 x3
y1 y2 y3
z1 z2 z3

However here is what I would like, but I don’t know how to handle 2 steps in islice :

x1 y1 z1
x2 y2 z2
x3 y3 z3
x1 y1 z1
x2 y2 z2
x3 y3 z3

>Solution :

with open('path/snip.txt', 'r') as f_input, open('path/snip_output.txt', 'w') as f_output:
    for line in f_input:
        xyz = line.split()
        x, y, z = xyz[0:3], xyz[3:6], xyz[6:9]
        for triple in zip(x, y, z):
            f_output.write(' '.join(triple) + '\n')

writes

1.9849207e-01 9.6169322e-02 1.5000000e-02
1.9993099e-01 9.6354487e-02 1.6090730e-02
2.0150793e-01 1.0630896e-01 1.5000000e-02
1.9993099e-01 9.6354487e-02 1.6090730e-02
2.0261176e-01 1.0536750e-01 1.6090730e-02
2.0150793e-01 1.0630896e-01 1.5000000e-02
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading