如何按行号从文件中读取特定行?

287

我正在使用 for 循环读取文件,但我只想读取特定的行,比如第 #26 行和 #30 行。有没有内置的功能可以实现这个要求呢?


1
可能重复:https://dev59.com/4HRB5IYBdhLWcg3wcm6d - Adam Matan
30个回答

5
with open("test.txt", "r") as fp:
   lines = fp.readlines()
print(lines[3])

test.txt是文件名
打印test.txt文件中的第四行


对于较大的文件,readlines 几乎没有扩展性。 - kta

4
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

罗杰,我最喜欢的家伙!这可以从一个with语句中受益。 - Hamish Grubijan

3
一个更好的、小的修改,适用于Alok Singhal的答案。
fp = open("file")
for i, line in enumerate(fp,1):
    if i == 26:
        # 26th line
    elif i == 30:
        # 30th line
    elif i > 30:
        break
fp.close()

3
你可以使用已经有人提到过的这种语法非常简单地完成,但这绝对是最简单的方法:
inputFile = open("lineNumbers.txt", "r")
lines = inputFile.readlines()
print (lines[0])
print (lines[2])

3
这个怎么样:
>>> with open('a', 'r') as fin: lines = fin.readlines()
>>> for i, line in enumerate(lines):
      if i > 30: break
      if i == 26: dox()
      if i == 30: doy()

1
没错,这种方法比Alok的方法效率低一些,但是我的方法使用了with语句 ;) - Hamish Grubijan

3

我更喜欢这种方法,因为它更通用,即您可以将其用于文件、f.readlines() 的结果、StringIO 对象等任何内容:

def read_specific_lines(file, lines_to_read):
   """file is any iterable; lines_to_read is an iterable containing int values"""
   lines = set(lines_to_read)
   last = max(lines)
   for n, line in enumerate(file):
      if n + 1 in lines:
          yield line
      if n + 1 > last:
          return

>>> with open(r'c:\temp\words.txt') as f:
        [s for s in read_specific_lines(f, [1, 2, 3, 1000])]
['A\n', 'a\n', 'aa\n', 'accordant\n']

3

以下是我的一些个人看法,仅供参考 ;)

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

3
如果你不介意导入的话,fileinput正好可以实现你所需要的功能(即你可以读取当前行的行号)。

2

简洁明了

要打印文本文件中的某些行,请创建“lines2print”列表,然后只需在枚举变量“in” lines2print列表时进行打印。 使用line.strip()或line.strip('\n')来消除额外的“\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]

或者如果列表很小,只需将列表作为列表键入到推导式中即可。
with open("filepath", 'r') as fp:
    [print(x.strip()) for ei,x in enumerate(fp) if ei in [26,30]]

1
要打印第三行,
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接