By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,349 Members | 1,302 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,349 IT Pros & Developers. It's quick & easy.

retaining newline characters when writing to file

P: n/a
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.
Jun 6 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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>

Jun 6 '06 #2

P: n/a
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.
Jun 6 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.