writelines() or write()
David Goodger
dgoodger at bigfoot.com
Fri Jun 23 21:52:41 EDT 2000
on 2000-06-23 16:27, dave white (dwhite2 at seas.upenn.edu) wrote:
> When I use writelines() and my strings have \r characters at the end
> somehow my output file only contains the last line. What's the correct
> way to write multiple lines to a file?
>
> strings = ['one \r', 'two \r', 'three \r}
> outfile.writelines(strings)
> ---
> outfile looks like this:
> 'three '
> ---
> What I want to have happen of course is:
> 'one '
> 'two '
> 'three '
Could it be, perhaps, that the last line is simply overwriting the first
two? You're specifying '\r', carriage return, which may not start a new line
first. On MacOS, \r is the line separator, but on Unix/Linux it's \n, and on
DOS/Windows it's both. Try this in the interactive interpreter:
>>> strings = ['one \r', 'two \r', 'three \r']
>>> f=open('tmpfile','w')
>>> f.writelines(strings)
>>> f.close()
>>> open('tmpfile','r').read()
'one \015two \015three \015'
(Don't use "print"! The interpreter will automatically escape all control
characters in expression statements, a handy debugging feature.) Do you get
the same result as above? Try using \n instead of \r in your code.
--
David Goodger dgoodger at bigfoot.com Open-source projects:
- The Go Tools Project: http://gotools.sourceforge.net
(more to come!)
More information about the Python-list
mailing list