Search code examples
pythonrowrows

Python read multiple rows and write them into one row in ASCII file


I am trying to read several lines (rows) and write them into another file as rows, which contain per row 4 rows of the read file. Here is what I am trying to do, unfortunately without succes:

Read file:

2623    831     6892    0
2353    1803    3425    0
1910    1823    3810    0
1637    1287    2811    0
2803    546     6609    0
1591    2157    2367    0
2167    1906    2665    0
3192    2168    8362    0
3903    1465    2011    0
2355    1801    2004    0
2390    796     5055    0
1703    1044    3441    0
1886    1328    2731    0
1496    1277    3074    0
1827    460     5992    0
1945    1785    2065    0
1983    1963    2818    0
1532    2229    6936    0
2449    5972    1918    0
2699    2007    1581    0

Desired write file:

2623    831     6892    0 2353  1803    3425    0 1910  1823    3810    0 1637  1287    2811    0 
2803    546     6609    0 1591  2157    2367    0 2167  1906    2665    0 3192  2168    8362    0
3903    1465    2011    0 2355  1801    2004    0 2390  796     5055    0 1703  1044    3441    0
1886    1328    2731    0 1496  1277    3074    0 1827  460     5992    0 1945  1785    2065    0
1983    1963    2818    0 1532  2229    6936    0 2449  5972    1918    0 2699  2007    1581    0

My script until now:

import itertools
from itertools import product
# sample data
name = ["File_A"]
k = 0
#
for j in name:
    print 'name =',j
    k = k+1
    f1 = open("{j}.txt".format(j=j))
    f2 = open("{j}_{k}.txt".format(j=j,k=k),"w")
       #f2.write('SF1' + '  ' + 'SF1' + '  ' + '\n')
    for i, line in enumerate(f1):
        print(repr(line))
        #f2.write(line + ' ')
        f2.writelines(itertools.islice(f1, 0, None, None))
        if i == 4:
           f2.write(line + '\n')
           i = 0
       #    f2.writelines(itertools.islice(f1, 4, None))
    #with open('VY_{k}'.format(k=k), 'a') as f1:
    #lines = f1.readlines()
    f2.close()
    f1.close()

I have read about product and panda, but I have not managed anything.


Solution

  • You do not need itertools for it. Simply you can:

    name = ["File_A"]
    k = 0
    #
    for j in name:
        print('name =',j)
        k = k+1
        f1 = open("{j}.txt".format(j=j))
        f2 = open("{j}_{k}.txt".format(j=j,k=k),"w")
        i = 0 
        for line in f1:
            i += 1
            f2.write(line.rstrip()+' ')
            if i % 4 == 0:
               f2.write('\n')
        f2.close()
        f1.close()
    

    It reads each line, strips the newline at the ends and writes it into the new file and every 4th lines adds the newline again.