[Tutor] Writing an "Alt-Enter"
Kent Johnson
kent37 at tds.net
Tue Jun 20 12:03:20 CEST 2006
URBAN LANDREMAN wrote:
> I'm trying to write a .csv file which I can subsequently load into Excel.
> The part that's tripping me up is I want to include an "Alt-Enter" between
> two of the fields so that when Excel reads the file, it will enter the two
> fields into the same cell, but on separate lines.
>
> Is there a way to do it with chr(x) or \nnn or something similar?
An easy experiment answers this. I created an Excel worksheet in this
format and saved it as csv. The resulting file has a newline in the
field and it is quoted so the newline is interpreted as part of the data
rather than the end of a record. Here is the data from the csv file:
A,"B
C",D
E,F,G
One way to write a csv file is with the csv module. It takes care of
adding quotes around any fields that need them. Here is code to write
your data using the csv module:
import csv
states = [
("MN", "Minnesota","St. Paul"),
("WI", "Wisconsin","Madison"),
("OH", "Ohio","Columbus"),
]
oFileName = "c:\PythonExport.csv"
ofile = open(oFileName,"wb")
ocsv = csv.writer(ofile)
ocsv.writerow(["State Code","State info"])
for stateCode, state, city in states:
stateInfo=[stateCode, state + '\n' + city]
ocsv.writerow(stateInfo)
ofile.close()
Notice that the argument to writerow() is a list of strings, and the
file must be opened in binary mode ("wb").
Kent
More information about the Tutor
mailing list