仅读取特定行 [英] Reading specific lines only
本文介绍了仅读取特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用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屋!
查看全文