reading from a text file

inhahe inhahe at gmail.com
Mon Nov 30 18:48:56 CET 2009


i don't understand the point of using 'with'
but i don't understand what 'with' does at all
i've tried to understand it a few times
anyway here:

import random
result = random.choice(open("c:\\test.txt").readlines())

On Mon, Nov 30, 2009 at 10:41 AM, Tim Golden <mail at timgolden.me.uk> wrote:
> Olof Bjarnason wrote:
>>
>> 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)
>
> Or, slightly more simply:
>
> import random
> with open ("c:/test.txt") as f:
>  print random.choice (list (f))
>
>
> You need the list () because random.choice only works
> on a finite iterable.
>
> TJG
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list