用 Python 将字符串列表写入 Excel CSV 文件 [英] Writing List of Strings to Excel CSV File in Python
问题描述
我正在尝试使用以下脚本创建一个包含 Python 字符串列表内容的 csv 文件.但是,当我检查输出文件时,发现每个字符都由逗号分隔.如何指示 csv.writer
分隔列表中的每个单独字符串而不是每个字符?
导入csv结果 = ['苹果','樱桃','橙色','菠萝','草莓']result_file = open("output.csv",'wb')wr = csv.writer(result_file,dialect='excel')对于结果中的项目:wr.writerow(项目)
我检查了 PEP 305 并且无法'没有找到任何具体的东西.
<代码>csv.writer writerow
方法将一个可迭代对象作为参数.您的结果集必须是列表(行)的列表(列).
csvwriter.writerow(row)
将 row 参数写入 writer 的文件对象,根据当前方言进行格式化.
执行以下任一操作:
导入csv结果 = [['苹果','樱桃','橙子','菠萝','草莓']]使用 open('output.csv','w') 作为 result_file:wr = csv.writer(result_file,dialect='excel')wr.writerows(结果)
或:
导入csv结果 = ['苹果','樱桃','橙色','菠萝','草莓']使用 open('output.csv','w') 作为 result_file:wr = csv.writer(result_file,dialect='excel')wr.writerow(结果)
I'm 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 csv.writer
to delimit every individual string within the list rather than every character?
import csv
RESULTS = ['apple','cherry','orange','pineapple','strawberry']
result_file = open("output.csv",'wb')
wr = csv.writer(result_file, dialect='excel')
for item in RESULTS:
wr.writerow(item)
I checked PEP 305 and couldn't find anything specific.
The csv.writer
writerow
method takes an iterable as an 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','w') as result_file:
wr = csv.writer(result_file, dialect='excel')
wr.writerows(RESULTS)
or:
import csv
RESULT = ['apple','cherry','orange','pineapple','strawberry']
with open('output.csv','w') as result_file:
wr = csv.writer(result_file, dialect='excel')
wr.writerow(RESULT)
这篇关于用 Python 将字符串列表写入 Excel CSV 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!