简体   繁体   中英

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?

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
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM