[Tutor] easy newbie questions: text file to list?

Jeff Shannon jeff@ccvcorp.com
Mon May 19 23:05:02 2003


ashleigh smythe wrote:

>Hello.  I have a text file that looks like this:
>
>Y16911
>AF202148
>U81576
>AF202159
>...
>
>I can get Python2.2 on my Linux to read the file with file.read() which
>makes it look like this:
>'Y16911\nAF202148\nU81576\n...'
>
>I would like to turn these items into a list (that I can save, not just
>work with in the interpreter) but I'm confused about strings and
>pickling etc.  I know that to save a list I have to pickle it (and I've
>succeeded at that for another list) but how do I get these into a list? 
>  
>

As someone else already said, you can either take the string you have 
and split() it on '\n', or you can use file.readlines() to read the 
entire thing into a list to begin with.  But why do you think you need 
to pickle this file?  You say that you want to save it... but isn't it 
already saved?  You can get the information you want from the text file 
just as easily as you could from a pickle.  A pickle might be warranted 
after you've done some extensive processing on each element of the 
list... but even there, it's quite possibly just as easy to write the 
list into another plain text file (and read it back in in the same way 
that you did this one) instead of pickling it.

Be careful about deciding too strongly on any particular tool before 
you've figured out an overall path to a solution.  In this case, from 
what you've said so far, it doesn't look (to me) like a pickle is likely 
to be the ideal tool to use.  The best way to make your data persistent 
(store it long-term) will depend on just what form the data takes and 
what you want to do with it, and data this simple is probably not a good 
match for a somewhat-complex storage tool like pickle.

Jeff Shannon
Technician/Programmer
Credit International