我使用for循环来读取文件,但我只想读取特定的行,比如第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()

其他回答

您可以执行seek()调用,将读头定位到文件中的指定字节。这对您没有帮助,除非您确切地知道在要读取的行之前文件中写入了多少字节(字符)。也许你的文件是严格格式化的(每一行是X个字节?)或者,如果你真的想提高速度,你可以自己计算字符的数量(记得包括不可见的字符,比如换行符)。

否则,您必须在您想要的行之前阅读每一行,就像这里已经提出的许多解决方案之一一样。

为了提供另一种解决方案:

import linecache
linecache.getline('Sample.txt', Number_of_Line)

我希望这是快速和简单的:)

file = '/path/to/file_to_be_read.txt'
with open(file) as f:
    print f.readlines()[26]
    print f.readlines()[30]

使用with语句打开文件,打印第26行和第30行,然后关闭文件。简单!

@OP,你可以使用枚举

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

这是我的2美分,不管它是否值得;)

def indexLines(filename, lines=[2,4,6,8,10,12,3,5,7,1]):
    fp   = open(filename, "r")
    src  = fp.readlines()
    data = [(index, line) for index, line in enumerate(src) if index in lines]
    fp.close()
    return data


# Usage below
filename = "C:\\Your\\Path\\And\\Filename.txt"
for line in indexLines(filename): # using default list, specify your own list of lines otherwise
    print "Line: %s\nData: %s\n" % (line[0], line[1])