此处希望在python中,将A和B的QA对话,中错误的对话,保存到csv中。
打算自己先创建一个csv文件,然后后续每个对话出错的话,就append追加写入到csv中。
其中希望用逗号分隔。而句子中如果有逗号,则用双引号扩起来
python csv
6.1 读写CSV数据 — python3-cookbook 2.0.0 文档
13.1. csv — CSV File Reading and Writing — Python 2.7.15 documentation
14.1. csv — CSV File Reading and Writing — Python 3.7.0 documentation
期间遇到:
【已解决】python中用codecs去写入csv出错:io.UnsupportedOperation: write
但是用代码:
with codecs.open(gCurInvalidSentenceFullFilename, "w", encoding="utf-8") as csvFp:
csvListWriter = csv.writer(csvFp)
csvListWriter.writerow(rowValueList)
出现个问题:
每次写入,都不是追加,而是覆盖,导致之前的headers和row,都被覆盖,只剩最后一行了:
python csv write append
Interacting with CSV files using Python – Bean Coder
把文件打开模式从w换成a(append):
# with codecs.open(gCurInvalidSentenceFullFilename, "w", encoding="utf-8") as csvFp:
with codecs.open(gCurInvalidSentenceFullFilename, "a", encoding="utf-8") as csvFp:
csvListWriter = csv.writer(csvFp)
csvListWriter.writerow(rowValueList)
结果:
就可以了
且可以注意到:
如果字符串中包含有双引号,则会用两个双引号扩起来,字符串内部的原先单个的双引号变成2个双引号
如果字符串中包含(本身csv的默认分隔符:)逗号,,则也会用左右双引号扩起来
-》就消除了我之前的这方面的担心了。
-〉然后去用工具打开看看表格效果:
(1)VSCode中csv插件
-》
无法显示
(2)excel
可以正常显示的。
然后试了试:
用list列表去保存值:
rowValueList = [mongoId, invalidReason.name, sentence]
with codecs.open(gCurInvalidSentenceFullFilename, "a", encoding="utf-8") as csvFp:
csvListWriter = csv.writer(csvFp)
csvListWriter.writerow(rowValueList)
或者用dict去保存值(需要指定header)
gInvalidSentenceCsvHeaders = [‘MongoID’, ‘Reason’, ‘Sentence’]
rowDict = {
"MongoID": mongoId,
# "Reason": str(invalidReason),
"Reason": invalidReason.name,
"Sentence": sentence
}
with codecs.open(gCurInvalidSentenceFullFilename, "a", encoding="utf-8") as csvFp:
csvDictWriter = csv.DictWriter(csvFp, fieldnames=gInvalidSentenceCsvHeaders)
csvDictWriter.writerow(rowDict)
都是可以保存csv数据的。
效果是:
转载请注明:在路上 » 【已解决】Python中创建和保存数据到csv文件中