Home > Software design >  Split .txt file rows in Python
Split .txt file rows in Python

Time:03-17

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 :

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

CodePudding user response:

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

CodePudding user response:

You can do this:

n = 3
values = []
with open("log.txt") as f, open("output.txt", 'w') as g:
    for line in f:
        lst = line.rstrip().split()
        for i in zip(*[lst[i:i   n] for i in range(0, len(lst), n)]):
            print(*i, file=g)

content of output.txt:

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

You need to split the returned list from line.rstrip().split() in to n chunks. Then with zip you can iterate through them in parallel.

  • Related