retaining newline characters when writing to file

J

John Salerno

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?

Example: In a CGI script, I'm reading the address field from an HTML
form. Almost always the person will press ENTER so they can enter a
second or third line. If I then want to write all the field values of
this form to a CSV file, so that each person's entries takes one line,
how can I ensure that the address string stays on one line despite the
newline characters?

(Or is it better to just use separate text fields for each line of the
address?)

Thanks.
 
F

Fredrik Lundh

John said:
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>
 
J

John Salerno

Fredrik said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top