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@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.


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to