<[EMAIL PROTECTED]> wrote: >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']
The problem is that read() just reads in characters of text and stores them in a string. It doesn't *execute* that text as if it were a program. You want to do one of two things. The first, which requires no changes to your file, would be to eval the text you read. For example: >>> s = "['foo', 'bar']" >>> s "['foo', 'bar']" >>> type (s) <type 'str'> s is a string containing the printed representation of a list. You turn that into a real list by passing the string to eval() >>> l = eval (s) >>> l ['foo', 'bar'] >>> type (l) <type 'list'> Alternatively (and probably the direction you want to be looking), is to alter your file a little and import it. Make your file look like: x = ['abc', 'def'] Assuming the filename is "foo.py", you can do "import foo" and your file will be read AND EXECUTED, and a module will be created with the same name as the basename of the file. The variable x will be a variable inside that module: >>> import foo >>> foo.x ['abc', 'def'] -- http://mail.python.org/mailman/listinfo/python-list