How to write List Object to a File??

Brian Quinlan BrianQ at ActiveState.com
Tue Apr 24 18:44:23 EDT 2001


I don't know for sure but it looks like you want each list element on a new
line in the file. If so, try this:

import os

a = ['a','b','c']

f = open( r'c:\test.txt', 'w' )
f.write( os.linesep.join( a ) )

f = open( r'c:\test.txt', 'r' )
# Just strips the surrounding whitespace from the line
b = [i.strip() for i in f.readlines( )]
print b

Ed wrote:
> I currently have a list and woulr like to store the contents into a
> text fiel whihc I can read back ...
>
> For example:
> a = ['a','b','c','d']
> #do something like
> fd = open('txt.txt','w')
> fd.write(a)
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> TypeError: read-only buffer, list
>
> What to do??
> And I can't use pickle ...
>
> later on I would like to read it back...
>
> fd = open('txt.txt','r')
>
> iniInfo = fd.readlines()
> b=[]
> b = iniInfo[0]
> # copy list contents into c
> map(c.append,b)
>
> I think this also not work right
> ?
> Can someone kindly tell me how to do write and read a list to a file?
>
> Thanks
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>





More information about the Python-list mailing list