2013-09-10 49 views
0

我有一個巨大的文件,該文件是這樣的:閱讀3號線然後每

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 

在蟒蛇我想讀每一個第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 
+0

更多imformations將是有益的。哪種語言?你有什麼嘗試? – Pr0gr4mm3r

+0

對不起,在python中。目前我只能第一次打印,但似乎無法找到一種方法來循環播放,並在文件結束之前繼續播放我想要的內容。希望這可以清除事情。 – Chino

回答

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

這應該工作,這需要i mod 8,因爲它看起來每個塊是8行長。不是最好的解決方案,你應該保持你的數據稍微整齊的格式。

或者更簡單:

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

如果不是((i + 1)%8)%3:' – xcorat

+0

@xcorat爲什麼?這似乎要複雜得多。如果你想讓它更簡單,爲什麼不'如果我%8 == 2或i%8 == 5:'? – placeybordeaux

+0

,因爲那裏只有一個比較,我認爲它的速度更快 – xcorat