[Tutor] read line x from a file
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Sun Jan 23 01:46:22 CET 2005
On Sat, 22 Jan 2005, Kent Johnson wrote:
> Jay Loden wrote:
> > One simple solution is to do:
> >
> > fle = open(file)
> > contents = file.readlines()
> > file.close()
> > print contents[x] #or store this in a variable, whatever
>
> That is the simplest solution. If your file gets bigger and you don't
> want to read it all at once, you can use enumerate to iterate the lines
> and pick out the one you want:
>
> f = open(...)
> for i, line in enumerate(f):
> if i==targetLine:
> print line # or whatever
> break
> f.close()
Hi everyone,
Here's a cute variation for folks who feel comfortable about iterators:
###
f = open(...)
interestingLine = itertools.islice(f, targetLine, None).next()
f.close()
###
This uses the remarkable 'itertools' library to abstract away the explicit
loop logic:
http://www.python.org/doc/lib/itertools-functions.html
For example:
###
>>> f = open('/usr/share/dict/words')
>>> print repr(itertools.islice(f, 31415, None).next())
'cataplasm\n'
>>> f.close()
###
This shows us that /usr/share/dict/word's 31416th word is 'cataplasm',
which we can double-check from the Unix shell here:
###
[dyoo at shoebox dyoo]$ head -n 31416 /usr/share/dict/words | tail -n 1
cataplasm
###
Best of wishes!
More information about the Tutor
mailing list