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


当前回答

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

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

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

其他回答

def getitems(iterable, items):
  items = list(items) # get a list from any iterable and make our own copy
                      # since we modify it
  if items:
    items.sort()
    for n, v in enumerate(iterable):
      if n == items[0]:
        yield v
        items.pop(0)
        if not items:
          break

print list(getitems(open("/usr/share/dict/words"), [25, 29]))
# ['Abelson\n', 'Abernathy\n']
# note that index 25 is the 26th item

相当快,切中要害。

打印文本文件中的某些行。创建一个“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]]
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()

如果你想读取特定的行,比如从某个阈值行开始的行,那么你可以使用下面的代码, File = open("files.txt","r") Lines = file.readlines() ##转换为行列表 data = lines[11:] ## raed特定的行

打印第3行,

line_number = 3

with open(filename,"r") as file:
current_line = 1
for line in file:
    if current_line == line_number:
        print(file.readline())
        break
    current_line += 1

原作者:Frank Hofmann