Lists and Files

Steve Holden sholden at holdenweb.com
Sun Apr 8 00:09:32 EDT 2001


"Eric Renouf" <erenouf at opticominc.com> wrote in message
news:3ACFDA73.AE956F03 at opticominc.com...
> Try using repr instead of string, then evalling the string when you read
it
> back in instead of trying to cast it to a list.
>
> fds.write(repr(stooges))
> ...
> no_longer_stooges = eval(fds.read())
>
> David Andreas Alderud wrote:
> I'm new to Python, started yesterday, is there a good way to handle lists
>
> > and files?
> >
> > For example:
> >
> >     stooges = ['val1', 'val2', 1, [['val2_1', 'val2_2', 0], ['val2_1',
> > 'val2_2', 0]]]
> >     fds = open("stooges", "w")
> >     # fds.write(stooges) doesn't work, maybe I can encapsulate and pack
it
> > to some other format, other than str that is, one that works?
> >     fds.write(str(stooges))
> >     fds.close()
> >     fds = open("stooges", "r")
> >     no_longer_stooges = list(fds.read())
> >     print no_longer_stooges
> >         =>
> >             ['[', "'", 'v', 'a', 'l', '1', "'", ',', ' ', "'", 'v', 'a',
> > 'l', '2', "'", ',', ' ', '1', ',', ' ', '[', '[', "'", 'v', 'a', 'l',
'2',
> > '_', '1', "'", ',', ' ', "'", 'v', 'a', 'l', '2', '_', '2', "'", ',', '
',
> > '0', ']', ',', ' ', '[', "'", 'v', 'a', 'l', '2', '_', '1', "'", ',', '
',
> > "'", 'v', 'a', 'l', '2', '_', '2', "'", ',', ' ', '0', ']', ']', ']']
> >
> > and that's not what I want, I could write a parser for the dynamic data
but
> > I rather not if there is a good way to handle it.
> > Someone _must_ have stumbled across this problem before me, as it seams
like
> > a common thing to do, and solved it, so I rather not duplicate the
effort,
> > any hits and pointers or full solutions?
> >
> > /Kind regards,
> >     David A. Alderud
>
David:

I think you would find the "marshall" and "pickle" module documentation
enlightening. Both of these will handle reading and writing Python objects
from/to files. Examine the different limitations and choose the appropriate
poison.

regards
 Steve






More information about the Python-list mailing list