Python读取特定的交替行

2024-09-24 08:24:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

现在我想先读第1行,第4行,第7行,第10行…,然后是第2行,第5行,第8行,。。。最后是第3行,第6行,第9行,…所以像这样我还想把这三组行写在另外三个单独的小文件中。有人能建议如何使用readlines()或其他类似的python方法吗?在


Tags: 文件文本建议文本文件line1readlinesline2line3
2条回答
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文件'是你的原始文件。在

使用%

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

相关问题 更多 >