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


当前回答

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

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

其他回答

您可以使用一种最简单的逻辑将字符串拆分为数组或List。

f = open('filepath')
r = f.read()
s = r.split("\n")
n = [linenumber1, linenumber2] # [26, 29] in your 
                               #case
for x in n:
  print(s[x-1])
f.close()

我更喜欢这种方法,因为它更通用,即你可以在文件上使用它,在f.r edlines()的结果上,在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']
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()

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

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

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

读取文件非常快。读取一个100MB的文件需要不到0.1秒(请参阅我的文章用Python读写文件)。因此,你应该完整地阅读它,然后处理单行。

大多数回答这里做的不是错,而是风格不好。打开文件应该总是用with,因为它可以确保文件再次关闭。

所以你应该这样做:

with open("path/to/file.txt") as f:
    lines = f.readlines()
print(lines[26])  # or whatever you want to do with this line
print(lines[30])  # or whatever you want to do with this line

巨大的文件

如果你有一个巨大的文件,内存消耗是一个问题,你可以逐行处理它:

with open("path/to/file.txt") as f:
    for i, line in enumerate(f):
        pass  # process line i