[Tutor] read line x from a file

Orri Ganel singingxduck at gmail.com
Sat Jan 22 05:38:34 CET 2005


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
>
Well, one way to do this is to count newlines, assuming you know what 
newline character your system uses.  For example (UNTESTED):

 >>> test = open("test.txt","r")   ## open the file
 >>> newline = []
 >>> tfile = test.read()
 >>> for i in range(len(tfile)):   ## instead of 'for char in tfile'
       if tfile[i] == '\n':      ## to make the index of each newline
          newline.append(i)      ## easier to find
 >>> import random
 >>> newl = random.choice(newline)
 >>> print tfile[newl:tfile[newl:].index('\n')]   ## prints tfile from the
## randomly selected newline index to the next newline index, or one line
## prints data here
 >>> test.close()

Now, this might not work, depending on whether or not '\n' is treated as 
a single character in this case. If not, you have to do a whole lot of 
the same sort of slicing as i did on the print line in order to find 
each successive newline (with tfile.index("\n")).


HTH,
Orri

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050121/0a6c8463/attachment.htm


More information about the Tutor mailing list