Reputation: 1437
Is there a more python friendly way to read 100 lines from a file, other than this way:
f=open(varFilename,"r")
count=0
for fileLine in f:
print fileLine
count+=1
if count>100:
break
I just feel like there is a better way than having a count increment and then try and break inside the loop.
Upvotes: 0
Views: 398
Reputation: 1122082
Use itertools.islice()
to limit the file object iterator to just 100 lines:
from itertools import islice
with open(filename) as f:
for line in islice(f, 100):
Here I'm also using the file object as a context manager; the with
statement ensures the file is closed again when the code block is exited.
If you don't need to limit the number of itertions but only need a counter in a loop, don't use a separate counter. Use enumerate()
instead:
for i, line in enumerate(f):
if i > 100:
Upvotes: 8
Reputation: 250961
You can use itertools.islice
to get just the first n
lines from file object:
from itertools import islice
with open(varFilename) as f:
for line in islice(f, 10):
#do something here
And use with
statement while handling files:
It is good practice to use the
with
keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
Upvotes: 6