问题
I'm having a problem...
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']
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)
Tks!!
回答1:
.writerow
takes an iterable and writes each item in the iterable as a column in your csv. It looks like you are passing a single string as row
. In this case, you'd want:
for website in data:
mycsv.writerow([website])
However, I'm guessing this isn't quite what you want since there is no need for csv
if you just want to write one item per line. The problem is probably in how you are specifying data
to the writeCsvFile
function. Perhaps you want the following:
data = [[u'www.rosenzweigco.com', u'www.investopedia.com', u'www.bk.mufg.jp']]
Notice that now data
is a list of lists. So when you iterate over it (for row in data
), you'll actually get a row (list
) instead of just a single string.
回答2:
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
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
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'])
来源:https://stackoverflow.com/questions/37618674/write-a-csv-without-delimiters-in-python