用Python编写不带定界符的CSV [英] Write a CSV without delimiters in Python

查看:192
本文介绍了用Python编写不带定界符的CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题...

我有许多网站的列表,例如此示例.

I have a list of a number of websites, like this example.

[u'www.rosenzweigco.com', u'www.investopedia.com', u'www.bk.mufg.jp']

但是,当我想要CSV文件时,就会收到此消息:

However, when I want to have a CSV file, I'm getting this:

w,w,w,.,r,o,s,e,n,z,w,e,i,g,c,o,.,c,o,m,
w,w,w,.,i,n,v,e,s,t,o,p,e,d,i,a,.,c,o,m,

我的代码如下(我不需要空格而不是逗号):

My code is the following (I need no space instead of the commas):

def writeCsvFile(fname,data):
mycsv = csv.writer(open(fname, 'wb'), delimiter=',',quoting=csv.QUOTE_NONE)
for row in data:
    mycsv.writerow(row)

谢谢!

推荐答案

第一个想到的主意与mgilson的答案相同. 另外,如果您使用的是python 3,则需要使用'w'参数打开文件,而与python 2.7

The first idea struck me is the same as mgilson's answer. Also, if you are using python 3 , you need to open file with 'w' parameter, without binary mode unlike the python 2.7

Python 3.5

Python 3.5

with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)

Python 2.7

Python 2.7

import csv
with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

这篇关于用Python编写不带定界符的CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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