<ed_tsang at yahoo.com> wrote in message news:mailman.988151437.3004.python-list at python.org... > 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'] It's a list of strings, then? Without newline characters at the end? And you want to write one per line? > #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?? Maybe simplest fd.writelines([x+'\n' for x in a]) for some definition of "simplest". You may expand the loops differently of course, e.g.: for x in a fd.write(x+'\n') If a is not a list of strings, you'll want to use str(x) rather than x in either of the above examples. > 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 I think it will separately append each character of the first line, though I haven't checked. > ? > Can someone kindly tell me how to do write and read a list to a file? fd.readlines() gives you a list -- but each string does have a trailing newline character of course. You can take it out in many ways, e.g. c.extend([x[:-1] for x in iniInfo]) Alex
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4