[Tutor] read line x from a file
Kent Johnson
kent37 at tds.net
Sat Jan 22 22:23:16 CET 2005
Max Noel wrote:
>
> 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).
enumerate() takes an iterator as an argument. The above program will read one line of the file at a
time; when the target line is reached it will be printed. The file will only be read up until the
target line.
Or maybe you mean that to select a target line you have to know how many lines are in the file? Yes,
I suppose you do...the OP wasn't very specific about how the line is selected...in that case
readlines() might be the simplest thing to do.
PS random.choice() might be handy here.
Kent
>
> -- 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