A problem with list
gawel
gawel at web-alternative.com
Mon Dec 13 10:06:08 EST 2004
export at hope.cz wrote:
> The following code
> ##############
> import string
> MyList=['abc','def']
> for i in MyList:
> print i
> ###############
>
> works as I expect that is I get
> abc
> def
>
> but when I have Mylist in a file and I read it from the file it does
> not work as I expect.
> #########
> import string
> ff=open('C:\\Robotp\\MyFile.txt','r') # read MyList from a file
> MyList=ff.read()
> for i in MyList:
> print i
> ###########
> I will get
> [
> '
> a
> b
> c
> '
> ,
> '
> d
> e
> f
> '
> ]
>
> where my MyFile.txt looks like this:
> ['abc','def']
>
> Where is a problem?
> Thanks for help
> Lad
>
That's quite simple. Your file contain a string, not a list
You must use eval(your_list_as_string).
>>> f = open('/tmp/list')
>>> f.seek(0)
>>> s = f.read()
>>> s
"['adc','def']\n"
>>> l = eval(s)
>>> l
['adc', 'def']
>>> for i in l:
... print i
...
adc
def
gawel
More information about the Python-list
mailing list