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()
i == n-1 for the
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
The quick answer:
f=open('filename') lines=f.readlines() print lines print lines
lines=[25, 29] i=0 f=open('filename') for line in f: if i in lines: print i i+=1
There is a more elegant solution for extracting many lines: linecache (courtesy of "python: how to jump to a particular line in a huge text file?", a previous stackoverflow.com question).
Quoting the python documentation linked above:
>>> import linecache >>> linecache.getline('/etc/passwd', 4) 'sys:x:3:3:sys:/dev:/bin/sh\n'
4 to your desired line number, and you're on. Note that 4 would bring the fifth line as the count is zero-based.
If the file might be very large, and cause problems when read into memory, it might be a good idea to take @Alok's advice and use enumerate().
for line in fileobjectas a quick solution for small files.
linecachefor a more elegant solution, which will be quite fast for reading many files, possible repeatedly.
enumerate()for files which could be very large, and won't fit into memory. Note that using this method might slow because the file is read sequentially.