如何从文件中读取特定行(按行号)? [英] How to read specific lines from a file (by line number)?

查看:84
本文介绍了如何从文件中读取特定行(按行号)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 for 循环读取文件,但是我只想读取特定的行,例如#26 #30 .有内置的功能可以实现这一点吗?

I'm using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?

推荐答案

如果要读取的文件很大,并且您不想一次读取内存中的整个文件:

If the file to read is big, and you don't want to read the whole file in memory at once:

fp = open("file")
for i, line in enumerate(fp):
    if i == 25:
        # 26th line
    elif i == 29:
        # 30th line
    elif i > 29:
        break
fp.close()

请注意,第 n 行的 i == n-1 .

在Python 2.6或更高版本中:

In Python 2.6 or later:

with open("file") as fp:
    for i, line in enumerate(fp):
        if i == 25:
            # 26th line
        elif i == 29:
            # 30th line
        elif i > 29:
            break

这篇关于如何从文件中读取特定行(按行号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆