2009/3/12 Emad Nawfal (عماد نوفل) <emadnaw...@gmail.com>: > Hi Tutors, > I've never had a situation in which this was useful for me, but I'm just > curious. > If there is a text file that has a list or number of lists in it, is there > is a way to read the lists in the file as lists, and not as a string. Sample > file attached.
For the individual lines, there are various solutions. eval() is easy but not recommended because of the security risk. There are several recipes in the Python cookbook - search for "safe eval". Python 2.6 includes ast.literal_eval() which does the job safely: In [1]: from ast import literal_eval In [4]: data = '''["this", "is", "a", "list"] ...: ["this", "is", "another", "list"] ...: ["this", "is","list", "#", "2"]''' In [5]: for line in data.splitlines(): ...: print literal_eval(line) ['this', 'is', 'a', 'list'] ['this', 'is', 'another', 'list'] ['this', 'is', 'list', '#', '2'] Extending from parsing a single line to parsing all the lines in a file is trivial. Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor