[Tutor] reading lists from a text file

Emad Nawfal (عماد نوفل) emadnawfal at gmail.com
Mon Mar 16 20:59:13 CET 2009


2009/3/12 Kent Johnson <kent37 at tds.net>

> 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
>


Thank you all for the answers.
-- 
لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.....محمد
الغزالي
"No victim has ever been more repressed and alienated than the truth"

Emad Soliman Nawfal
Indiana University, Bloomington
http://emnawfal.googlepages.com
--------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090316/63560962/attachment.htm>


More information about the Tutor mailing list