Im trying to take a text file and use only the first 30 lines of it in python.
this is what I wrote:
text = open("myText.txt")
lines = myText.readlines(30)
print lines
for some reason I get more then 150 lines when I print?
What am I doing wrong?
The
sizehintargument forreadlinesisn’t what you think it is (bytes, not lines).If you really want to use
readlines, trytext.readlines()[:30]instead.Do note that this is inefficient for large files as it first creates a list containing the whole file before returning a slice of it.
A straight-forward solution would be to use
readlinewithin a loop (as shown in mac’s answer).To handle files of various sizes (more or less than 30), Andrew’s answer provides a robust solution using
itertools.islice(). To achieve similar results withoutitertools, consider:or as a generator expression (Python >2.4):