![]() |
Available news archives:
comp.lang.tcl
-
comp.lang.python
-
comp.security.firewalls
-
sci.crypt -
comp.lang.php -
comp.lang.javascript
|
|
comp.lang.python archiveRe: why writing list to file puts each item from list on seperate line?
From: Steven D'Aprano <steve@REMOVETHIScyber.com.au>
Date: Sat Dec 31 2005 - 05:52:30 CET
On Fri, 30 Dec 2005 20:22:52 -0800, homepricemaps wrote:
> if i use the code below to write a list to a file
Why are you shadowing the built in type list? This is bad practice. Sooner
list = [1, 2, 3]
and then you'll spend ages trying to work out why list() raises an
> data.append(list)
That's what you told it to do. Walk through the code:
>>> data = []
So far so good. But now watch:
>>> f = open(r"test.txt", 'a')
I hope you aren't opening the file EVERY time you want
>>> f.write(os.linesep.join(L))
Remember what L is: ("apple", "0.49", "market"). You now join that list
What happened to data? It never gets used after you append to it.
> and i want it to do
Then what you want to do is change data to a list of strings rather than
data.append(", ".join(L) + "\n") # note newline at the end of each line
Then, after you have appended ALL the lines, you open your file once for
f.writelines(data)
Hope this helps.
-- Steven.Received on Tue Jan 3 03:28:30 2006 |