[Tutor] Writing/reading lists to a file

Hans Dushanthakumar Hans.Dushanthakumar at navman.com
Wed Dec 28 04:38:29 CET 2005


Hi,
   Is there any easy way of writing lists to a file and more
importantly, reading it back as a list of lists rather than as a list of
strings.

Eg:

>>> t = ["t1", "PASS", 31]
>>> f = open("pass.txt","a+")
>>> f.write(str(t) + "\n")
>>> f.write(str(t) + "\n")
>>> f.close()

At this stage, the file contains two lines.

Now, if I use the readlines() function to read it back, heres what I
get:
>>> f = open("pass.txt","r+")
>>> r = f.readlines()
>>> r
["['t1', 'PASS', 31]\n", "['t1', 'PASS', 31]\n", "['t1', 'PASS', 31]\n"]
>>> r[0]
"['t1', 'PASS', 31]\n"

So, r[0] is now a string. Is there ant direct way of extracting the list
from this string?

Or alternatively, can I read the file as a list of lists rather than
list of strings (which is what readlines() appears to do).

Thanks,
Hans


More information about the Tutor mailing list