0

我有一个巨大的文件,看起来像这样:

Name: Block of line 1
Data: Block of line 2
**Important line 3**
Not important line 4
Not important line 5
**Another important line 6**
Not important line 7

Name: Block of line 1
Data: Block of line 2
**Important line 3**
Not important line 4
Not important line 5
**Another important line 6**
Not important line 7

Name: Block of line 1
Data: Block of line 2
**Important line 3**
Not important line 4
Not important line 5
**Another important line 6**
Not important line 7

在 python 中,我想读取每第 3 行和第 6 行,或者当我使用 .read() 时,它会成为第 2 行和第 5 行

我的代码只打印第一个块,所以理想情况下我想循环它:

files = open(fo, 'r')
for i, line in enumerate(files):
    if i == 2:
    print line
elif i == 5:
        print line
        break
4

1 回答 1

0
files = open(fo, 'r')
for i, line in enumerate(files):
    if i%8 == 2:
        print line
    elif i%8 == 5:
        print line

这应该可行,这需要imod 8,因为每个块似乎有 8 行长。不是最好的解决方案,您可能应该以稍微整洁的格式保存您的数据。

或者更简单:

files = open(fo, 'r')
for i, line in enumerate(files):
    if i%8 == 2 or i%8 == 5:
        print line
于 2013-09-10T20:17:34.113 回答