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

287

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


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

1

@楼主,你可以使用enumerate函数

for n,line in enumerate(open("file")):
    if n+1 in [26,30]: # or n in [25,29] 
       print line.rstrip()

1
file = '/path/to/file_to_be_read.txt'
with open(file) as f:
    print f.readlines()[26]
    print f.readlines()[30]

使用with语句,打开文件,打印第26和30行,然后关闭文件。简单易懂!

第一次调用readlines()后,迭代器将被耗尽,第二次调用将返回一个空列表或抛出错误(记不清了)。 - Paul H

1

0

打印所需的行。 打印所需行上方/下方的行。

def dline(file,no,add_sub=0):
    tf=open(file)
    for sno,line in enumerate(tf):
        if sno==no-1+add_sub:
         print(line)
    tf.close()

执行---->dline("D:\dummy.txt",6) 即 dline("文件路径", 行号, 如果你想要搜索行的上一行则输入1,如果要下一行则输入-1,这是可选项,默认值为0)


0

您可以使用最简单的逻辑之一,将字符串拆分为数组或列表来完成它。

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

0
如果您想读取特定行,例如在某个阈值行之后开始的行,则可以使用以下代码: file = open("files.txt","r") lines = file.readlines() ## 转换为行列表 datas = lines[11:] ## 读取特定行


0

不要使用readlines

我的解决方案是:


with open(filename) as f:
    specify = [26, 30]
    results = list(
        map(lambda line: line[1],
            filter(lambda line: line[0] in specify,
                   enumerate(f))
            )
    )

测试如下,针对一个 6.5G 的文件:

import time

filename = 'a.txt'
start = time.time()
with open(filename, 'w') as f:
    for i in range(10_000_000):
        f.write(f'{str(i)*100}\n')       
end1 = time.time()

with open(filename) as f:
    specify = [26, 30]
    results = list(
        map(lambda line: line[1],
            filter(lambda line: line[0] in specify,
                   enumerate(f))
            )
    )
end2 = time.time()
print(f'write time: {end1-start}')
print(f'read time: {end2-end1}')
# write time: 14.38945460319519
# read time: 8.380386352539062

-1

我认为这会起作用

 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]

当您发布此帖子时,已经有了十几种readline方法 - 添加另一个只会增加混乱。 - duhaime

-2
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()

8
这就是最不符合Python风格的写法。 - SilentGhost
会得到错误的结果,因为您不能像那样使用readlines和readline(它们都会更改当前读取位置)。 - Roger Pate
非常抱歉在我的第一个代码中忽略了一个巨大的错误。已经纠正了这个错误,当前的代码应该可以按照预期工作。感谢Roger Pate指出我的错误。 - inspectorG4dget

-2

从特定行读取:

n = 4   # for reading from 5th line
with open("write.txt",'r') as t:
     for i,line in enumerate(t):
         if i >= n:             # i == n-1 for nth line
            print(line)

这不是一个内置功能。 - Sven

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