我使用for循环来读取文件,但我只想读取特定的行,比如第26行和第30行。是否有任何内置功能来实现这一点?


当前回答

为了完整起见,这里还有一个选项。

让我们从python文档中的定义开始:

通常包含序列的一部分的对象。slice使用下标符号[]创建,当给出几个数字时,数字之间使用冒号,例如variable_name[1:3:5]。括号(下标)表示法在内部使用切片对象(或在旧版本中使用__getslice__()和__setslice__())。

虽然slice表示法一般不直接适用于迭代器,但itertools包包含一个替换函数:

from itertools import islice

# print the 100th line
with open('the_file') as lines:
    for line in islice(lines, 99, 100):
        print line

# print each third line until 100
with open('the_file') as lines:
    for line in islice(lines, 0, 100, 3):
        print line

该函数的另一个优点是,它直到结束才读取迭代器。所以你可以做更复杂的事情:

with open('the_file') as lines:
    # print the first 100 lines
    for line in islice(lines, 100):
        print line

    # then skip the next 5
    for line in islice(lines, 5):
        pass

    # print the rest
    for line in lines:
        print line

为了回答最初的问题:

# how to read lines #26 and #30
In [365]: list(islice(xrange(1,100), 25, 30, 4))
Out[365]: [26, 30]

其他回答

f = open(filename, 'r')
totalLines = len(f.readlines())
f.close()
f = open(filename, 'r')

lineno = 1
while lineno < totalLines:
    line = f.readline()

    if lineno == 26:
        doLine26Commmand(line)

    elif lineno == 30:
        doLine30Commmand(line)

    lineno += 1
f.close()

@OP,你可以使用枚举

for n,line in enumerate(open("file")):
    if n+1 in [26,30]: # or n in [25,29] 
       print line.rstrip()

相当快,切中要害。

打印文本文件中的某些行。创建一个“lines2print”列表然后 当枚举“在”lines2print列表中时,只需打印。 要去除多余的'\n',请使用line.strip()或line.strip('\n')。 我只是喜欢“列表理解”,并尽可能地使用它。 我喜欢用“with”方法来读取文本文件,以防止 以任何理由打开文件。

lines2print = [26,30] # can be a big list and order doesn't matter.

with open("filepath", 'r') as fp:
    [print(x.strip()) for ei,x in enumerate(fp) if ei in lines2print]

或者如果list很小,只需在理解式中输入list作为列表。

with open("filepath", 'r') as fp:
    [print(x.strip()) for ei,x in enumerate(fp) if ei in [26,30]]

如果您的大型文本文件是严格结构良好的(意味着每一行都有相同的长度l),您可以使用第n行

with open(file) as f:
    f.seek(n*l)
    line = f.readline() 
    last_pos = f.tell()

这只适用于具有相同长度的文件!

如果要读取的文件很大,并且你不想一次在内存中读取整个文件:

fp = open("file")
for i, line in enumerate(fp):
    if i == 25:
        # 26th line
    elif i == 29:
        # 30th line
    elif i > 29:
        break
fp.close()

注意第n行i == n-1。


在Python 2.6或更高版本中:

with open("file") as fp:
    for i, line in enumerate(fp):
        if i == 25:
            # 26th line
        elif i == 29:
            # 30th line
        elif i > 29:
            break