python字符串写入excel-在Python中将字符串列表写入Excel CSV文件

1586010002-jmsa.png

I am trying to create a csv file that contains the contents of a list of strings in Python, using the script below. However when I check my output file, it turns out that every character is delimited by a comma. How can I instruct the CSV.writer to delimit every individual string within the list rather than every character? In this case, I am using Python 2.6 on Snow Leopard.

I checked the Python guide and couldn't find anything specific:

http://www.python.org/dev/peps/pep-0305/#managing-different-dialects

import csv

# Define Data

RESULTS = ['apple','cherry','orange','pineapple','strawberry']

# Open File

resultFyle = open("output.csv",'wb')

# Create Writer Object

wr = csv.writer(resultFyle, dialect='excel')

# Write Data to File

for item in RESULTS:

wr.writerow(item)

解决方案

The csv.writer writerow method takes an iterable as argument. Your result set has to be a list (rows) of lists (columns).

csvwriter.writerow(row)

Write the row parameter to the writer’s file object, formatted according to the current dialect.

Do either:

import csv

RESULTS = [

['apple','cherry','orange','pineapple','strawberry']

]

with open("output.csv",'wb') as resultFile:

wr = csv.writer(resultFile, dialect='excel')

wr.writerows(RESULTS)

or:

import csv

RESULT = ['apple','cherry','orange','pineapple','strawberry']

with open("output.csv",'wb') as resultFile:

wr = csv.writer(resultFile, dialect='excel')

wr.writerow(RESULT)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值