[英]Python: csv.writerow() splitting a key character by character?
Given: 鉴于:
import csv
def writeToCsv(rows):
with open('results.csv', 'w') as csvfile:
fieldnames = ['Name', '#Reviews', 'Address', 'Phone']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for row in rows:
writer.writerow(row)
When I attempt: 当我尝试:
row = {
'Name': self.validEntries.keys()[0],
'#Reviews': self.validEntries.values()[0],
'Address': (nap[0] + ', ' + nap[1]),
'Phone': nap[2]
}
writeToCsv(row)
I get: 我得到:
ValueError: dict contains field not in fieldnames: 'P', 'h', 'o', 'n', 'e'
Why is writerow
splitting this field (I imagine it will do the same for each field) character by character? 为什么writerow
拆分该字段(我想它将对每个字段执行相同的操作)?
You should pass the dictionary
into the writer.writerow
, instead of passing each key
into the write rows seperately. 您应该将dictionary
传递给writer.writerow
,而不是将每个key
分别传递给写入行。
Also, if you want to write multiple rows (meaning list of multiple dictionaries) into the csv together, you can use - writer.writerows(rows)
passing the list of diciontaries into it. 另外,如果要将多个行(表示多个词典的列表)一起写入csv,则可以使用writer.writerows(rows)
将词典的列表传递到其中。
Example - 范例-
import csv
with open('results.csv', 'w') as csvfile:
fieldnames = ['Name', '#Reviews', 'Address', 'Phone']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
row = {'Name':'Blah','#Reviews':'Blah','Address':'Blah','Phone':'Blah'}
writer.writeheader()
writer.writerow(row)
rows = [{'Name':'Blah2','#Reviews':'Blah2','Address':'Blah2','Phone':'Blah2'},{'Name':'Blah1','#Reviews':'Blah1','Address':'Blah1','Phone':'Blah1'}]
writer.writerows(rows)
After this the results.csv
looks like - 之后, results.csv
看起来像-
Name,#Reviews,Address,Phone
Blah,Blah,Blah,Blah
Blah2,Blah2,Blah2,Blah2
Blah1,Blah1,Blah1,Blah1
In your case you need to use writer.writerow(rows)
without looping through the rows. 在您的情况下,您需要使用writer.writerow(rows)
而不循环浏览各行。
Or you can also send in a list of rows as writeToCsv([row])
, but then still you do not need to iterate over the rows, you should use writer.writerows()
to write the rows into the dictionary. 或者,您也可以以writeToCsv([row])
发送行列表,但是仍然不需要遍历行,则应使用writer.writerows()
将行写入字典。 (notice the extra s
) (注意多余s
)
I think you have to change the code to: 我认为您必须将代码更改为:
row = {'Name': self.validEntries.keys()[0], '#Reviews' : self.validEntries.values()[0], 'Address' : (nap[0] + ', ' + nap[1]), 'Phone': nap[2]}
writeToCsv([row])
Your writeToCsv expecting a list not a dict. 您的writeToCsv需要列表而不是字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.