在Python中将字符串列表写入Excel CSV文件 [英] Writing List of Strings to Excel CSV File in Python

查看:3248
本文介绍了在Python中将字符串列表写入Excel CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个csv文件,其中包含Python中的字符串列表的内容,使用下面的脚本。但是,当我检查我的输出文件,结果是每个字符用逗号分隔。如何指示CSV.writer分隔列表中的每个字符串,而不是每个字符?在这种情况下,我在Snow Leopard上使用Python 2.6。



我检查了Python指南,发现没有什么特别的:

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

  import csv 

#定义数据
RESULTS = ['apple','cherry','orange','pineapple','strawberry']

#打开文件
resultFyle = open(output.csv,'wb')

#创建Writer对象
wr = csv.writer(resultFyle,dialect ='excel')
b $ b#将数据写入文件
对于结果中的项目:
wr.writerow(item)


解决方案

csv.writer writerow 方法使用iterable作为参数。您的结果集必须是列表(列)的列表(行)。


  csvwriter。 writerfor(row)

将行参数写入到写入器的文件对象,根据当前的方言格式化。


执行以下操作之一:

  import csv 
RESULTS = [
['apple','cherry','orange','pineapple','strawberry']
]
with open ,'wb')as resultFile:
wr = csv.writer(resultFile,dialect ='excel')
wr.writerows(RESULTS)
pre>

或:

  import csv 
RESULT = ['apple','cherry','orange','pineapple','strawberry']
with open(output.csv,'wb')as resultFile:
wr = csv.writer (resultFile,dialect ='excel')
wr.writerow(RESULT)


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)

这篇关于在Python中将字符串列表写入Excel CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆