reading from a text file

Olof Bjarnason olof.bjarnason at gmail.com
Mon Nov 30 08:05:31 EST 2009


2009/11/27 baboucarr sanneh <sanneh27 at hotmail.com>:
> hi all
>
> i would like to create a python program that would read from a text file and
> returns one result at random.
> e.g
> in the text file i have these data
>
> 1.hello
> 2.my name
> 3.is
> 4.World
>
> Your help is highly appreciated..thnx in advance

Hi babourarr;

import random
with open("c:/test.txt") as f:
  lines = f.read().splitlines()
random_line = lines[random.randrange(len(lines))]
print(random_line)

>
> $LIM $H at DY
>
>
> ________________________________
> Windows Live: Friends get your Flickr, Yelp, and Digg updates when they
> e-mail you.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



-- 
twitter.com/olofb
olofb.wordpress.com
olofb.wordpress.com/tag/english



More information about the Python-list mailing list