简体   繁体   中英

writing a simple list as column headers using .csv in python 2.7

I have a simple list made of five items. I want to write this as headers to columns to an existing .csv that has data on all five columns. The issue is that I cannot get to write each item as one single cell to column headers. Also, I need to use just Python 2.7 as I'll use it in IronPython (that does not support Pandas/etc. - other solutions).
Below is my simple code:

writefile =  r'E:\myfile.csv'
data = ['COLUMN A', 'COLUMN B', 'COLUMN C', 'COLUMN D', 'COLUMN E']
with open(writefile, 'w') as f:
    writer = csv.writer(f)
    writer.writerow(data)

The result is 10 columns:

"COLUMN", "A", "COLUMN", "B", "COLUMN", "C", "COLUMN", "D", "COLUMN", "E".

The desired result is with only five columns:

"COLUMN A", "COLUMN B", "COLUMN C", "COLUMN D", "COLUMN E".

You should have the csv module quote your strings for you:

Code:

writefile =  r'./myfile.csv'
data = ['COLUMN A', 'COLUMN B', 'COLUMN C', 'COLUMN D', 'COLUMN E']
with open(writefile, 'w') as f:
    writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
    writer.writerow(data)

Produces:

"COLUMN A","COLUMN B","COLUMN C","COLUMN D","COLUMN E"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM