retaining newline characters when writing to file

John Salerno johnjsal at NOSPAMgmail.com
Tue Jun 6 11:19:41 EDT 2006


Fredrik Lundh wrote:
> 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>
> 

Thanks. I should give the csv module a look too, while I'm at it.



More information about the Python-list mailing list