[Tutor] read line x from a file

Max Noel maxnoel_fr at yahoo.fr
Sat Jan 22 15:01:20 CET 2005


On Jan 22, 2005, at 13:53, Kent Johnson wrote:

> 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()

	Of course, to do that, you must know the number of lines in the file 
beforehand. If you're running a UNIX system (Linux, OS X, *BSD...), 
that's easily done by calling the command "wc -l <filename>" (use 
os.popen to do that).

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"



More information about the Tutor mailing list