[Tutor] read line x from a file

Kent Johnson kent37 at tds.net
Sat Jan 22 14:53:01 CET 2005


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

BTW try to avoid using 'file' as the name of a variable, it is a builtin function (or type, actually).

Kent

> 
> -Jay
> 
> On Friday 21 January 2005 11:22, J. M. Strother wrote:
> 
>>I have  a text file containing 336 records.
>>I can read and print out the whole file without any problem.
>>What I want to do is read and print out one record only (chosen at
>>random). So I need to get to record x, select it, and then print it (or
>>store it in a variable).
>>Can anyone tell me now to do this?
>>
>>I'm new to Python and programming, so sorry if this is very basic. Thanks.
>>
>>jon
>>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list