Lists and Files
Eric Renouf
erenouf at opticominc.com
Sat Apr 7 23:28:22 EDT 2001
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
--
Eric Renouf
Software Engineer
Opticom Inc.
www.getiview.com
More information about the Python-list
mailing list