[Tutor] reading lists from a text file

Kent Johnson kent37 at tds.net
Thu Mar 12 20:10:28 CET 2009


2009/3/12 Emad Nawfal (عماد نوفل) <emadnawfal at 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


More information about the Tutor mailing list