retaining newline characters when writing to file
Fredrik Lundh
fredrik at pythonware.com
Tue Jun 6 11:04:59 EDT 2006
John Salerno wrote:
> If I read a string that contains a newline character(s) into a variable,
> then write that variable to a file, how can I retain those newline
> characters so that the string remains on one line rather than spans
> multiple lines?
you cannot: the whole point of a newline character is to start a new line.
however, some file formats let you "escape" the newline. for example,
in Python source code, you can use end a line with a backslash. in CSV,
you can put the string with newlines inside quotes, and Python's "csv"
module knows how to do that:
import csv, sys
row = ("One\nTwo\nThree", 1, 2, 3)
writer = csv.writer(sys.stdout)
writer.writerow(row)
prints
"One
Two
Three",1,2,3
(not all CSV readers can handle multiline rows, though)
</F>
More information about the Python-list
mailing list