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?
Advertisement
Answer
If the file to read is big, and you don’t want to read the whole file in memory at once:
JavaScript
x
10
10
1
fp = open("file")
2
for i, line in enumerate(fp):
3
if i == 25:
4
# 26th line
5
elif i == 29:
6
# 30th line
7
elif i > 29:
8
break
9
fp.close()
10
Note that i == n-1
for the n
th line.
In Python 2.6 or later:
JavaScript
1
9
1
with open("file") as fp:
2
for i, line in enumerate(fp):
3
if i == 25:
4
# 26th line
5
elif i == 29:
6
# 30th line
7
elif i > 29:
8
break
9