Python读取特定的备用行

时间:2015-08-14 12:27:56

标签: python

我有一个大文本文件,我想从中读取特定行并将其写入另一个小文件中。例如,在我的文字中

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

现在我首先要读取line1,line4,line7,line10 ...,然后是line2,line5,line8,...然后最后是line3,line6,line9,....所以这样我也想将所有三组线写在另一个单独的三个小文件中。任何人都可以建议如何使用readlines()或其他类似的python方法?

2 个答案:

答案 0 :(得分:2)

使用%

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

答案 1 :(得分:0)

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'是目录中存在所有相关文件的绝对路径。 'tmp.txt'是您的原始文件。