There are >10 million lines in a file and the total file size is 19GB, I need to get only the 2nd line.
Getting a specific line could have been done with a loop:
for i,j in enumerate(open('foobar.txt')):
if i == 1:
print j
break
Or with linecache
(but not for large file, since it loads everything to the RAM)
import linecache
print linecache.getline(open('foobar.txt'),2)
or with unix
commands and os.popen
:
import os
infile = 'foobar.txt'
print os.popen('head -2 '+infile+'|tail -1')
I am exploring more options to get only the 2nd line.
\\n
and then stop reading? (this way it saves RAM space) I assume the question is scalable, given that the x in the xth line that someone is small and the size of the file is >>>.
You can do the same with itertools.islice
like this:
import itertools
n = 1
with open('foobar.txt') as f:
print next(itertools.islice(f, n, n+1))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.