physics_for_all
physics_for_all

Reputation: 2263

Python read specific alternate lines

I have a large text file from which I want to read specific lines and write them in another small files. For example, in my text

line1
line2
line3 
line4
line5
line6
line7
line8
line9
line10
...

Now first I want to read line1, line4, line7, line10..., then line2, line5, line8,... and then finally line3, line6, line9,....so like this I also want to write all three groups of lines in another separate three small files. Could any one suggests how to use readlines() or some other similar python method?

Upvotes: 1

Views: 2543

Answers (2)

Vivek Anand
Vivek Anand

Reputation: 651

import os

d = '/home/vivek/t'
l = os.listdir(d)

for i in l:
    p = os.path.join(d, i)
    if os.path.isfile(p) and i == 'tmp.txt':

        with open(p, 'r') as f:
            for index, line in enumerate(f.readlines()):
                if index % 3 == 0:
                    with open(os.path.join(d, 'store_1.txt'), 'a') as s1:
                        s1.write(line)
                elif index % 3 == 1:
                    with open(os.path.join(d, 'store_2.txt'), 'a') as s2:
                        s2.write(line)
                elif index % 3 == 2:
                    with open(os.path.join(d, 'store_3.txt'), 'a') as s3: 
                        s3.write(line)

'd' is the absolute path to the directory where all the associated files with the program is present. 'tmp.txt' is your original file.

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81654

Use %:

for index, line in enumerate(my_file.readlines()):
    if (index + 1) % 3 == 1: # means lines 1, 4 ,7, 10..
        # write line to file1
    elif (index + 1) % 3 == 2: # means lines 2, 5 ,8..
        # write line to file2 
    else: # means lines 3, 6, 9
        # write line to file3

Upvotes: 3

Related Questions