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


当前回答

打印第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

其他回答

读取文件非常快。读取一个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

@OP,你可以使用枚举

for n,line in enumerate(open("file")):
    if n+1 in [26,30]: # or n in [25,29] 
       print line.rstrip()
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()

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

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

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