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


当前回答

你可以用已经有人提到过的语法很简单地做到这一点,但这是迄今为止最简单的方法:

inputFile = open("lineNumbers.txt", "r")
lines = inputFile.readlines()
print (lines[0])
print (lines[2])

其他回答

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

让我们从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]
file = '/path/to/file_to_be_read.txt'
with open(file) as f:
    print f.readlines()[26]
    print f.readlines()[30]

使用with语句打开文件,打印第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()

我认为这行得通

 open_file1 = open("E:\\test.txt",'r')
 read_it1 = open_file1.read()
 myline1 = []
 for line1 in read_it1.splitlines():
 myline1.append(line1)
 print myline1[0]

文件对象有一个.readlines()方法,它将为您提供文件内容的列表,每个列表项一行。在此之后,您可以使用普通的列表切片技术。

http://docs.python.org/library/stdtypes.html#file.readlines