DictWriter.writerow为什么不将任何内容写入csv文件?

时间:2019-01-01 07:18:54

标签: python csv

我想将一些数据写入csv文件。但是除了标题(单词和数字)之外,什么也没写。我的代码有什么问题?

这是我的代码。

import os
import csv

csvFile = open('Trail.csv','w+')
fieldname = ['words', 'number']
trialDict = {'apple':1, 'banana':4, 'cat':6}
writer = csv.DictWriter(csvFile, fieldnames=fieldname, extrasaction='ignore')
writer.writeheader()
writer.writerow(trialDict)
csvFile.close()

我想要你的意思,我修改了我的代码。但是仍然存在问题。

import os
import csv

csvFile = open('Trail.csv','w+')
fieldname = ['words', 'number']
trialDict = {'words':'apple', 'number':5, 'words':'banana','number':6, 'words':'cat', 'number':5}
writer = csv.DictWriter(csvFile, fieldnames=fieldname, extrasaction='ignore') writer.writeheader()
writer.writerow(trialDict)
csvFile.close()

输出变为:

word numbers
cat   5

如何将所有内容写入文件?我尝试了writerows函数,但返回了错误:

str object has no attribute get()

3 个答案:

答案 0 :(得分:1)

这里的真正问题是,您正在用TrialDict覆盖密钥,并且仅使用Rating1_Clickprotected void Rating1_Click(object sender, RatingEventArgs e) { label3.Text = Rating1.CurrentRating.ToString(); } 的最后两个实例。

var date = new Date(/* whatever */);
var minutes = 3;
date.setMinutes(date.getMinutes() + minutes);
console.log(date)

您想要做的是拥有一个按词计数的字典,然后编写键,值对:

words

答案 1 :(得分:0)

字段名称是标题,您应该在字典中包含与标题对应的键,如果这是您的要求,则此代码应该起作用:

import os 
import csv

csvFile = open('Trail.csv','w+')
fieldname = ['apple', 'banana', 'cat']
trialDict = {'apple':1, 'banana':4, 'cat':6}
writer = csv.DictWriter(csvFile, fieldnames=fieldname, extrasaction='ignore')
writer.writeheader()
writer.writerow(trialDict)

csvFile.close()

答案 2 :(得分:0)

您不需要DictWriter。标准writer有效。根据{{​​3}}打开文件时,还请注意newline=''参数:

import csv

fieldname = ['words', 'number']
trialDict = {'apple':1, 'banana':4, 'cat':6}

with open('Trail.csv','w',newline='') as csvFile:
    writer = csv.writer(csvFile)
    writer.writerow(fieldname)
    for key,value in trialDict.items():
        writer.writerow([key,value])

输出:

words,number
apple,1
banana,4
cat,6

要使用DictWriter,您需要一个字典列表,这些字典的键为标头值:

import csv

fieldname = ['words', 'number']
trialList = [{'words':'apple','number':1},
             {'words':'banana','number':4},
             {'words':'cat','number':6}]

with open('Trail.csv','w',newline='') as csvFile:
    writer = csv.DictWriter(csvFile,fieldnames=fieldname)
    writer.writeheader()
    writer.writerows(trialList)