簡體   English   中英

讀取文件的第三行,然后每

[英]Read 3rd line of file and then every

我有一個很大的文件,看起來像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM