折腾:
期间,用代码:
<code>import csv import codecs def saveInvalidSentence(mongoId, sentence, invalidReason): """save invalid sentence and invalid reason""" global gCurInvalidSentenceFullFilename, gInvalidSentenceCsvHeaders if "," in sentence: logging.warning("Need know how to save it") rowDict = { "MongoID": mongoId, # "Reason": str(invalidReason), "Reason": invalidReason.name, "Sentence": sentence } rowValueList = [mongoId, invalidReason.name, sentence] with codecs.open(gCurInvalidSentenceFullFilename, "r", encoding="utf-8") as csvFp: csvListWriter = csv.writer(csvFp) csvListWriter.writerow(rowValueList) csvDictWriter = csv.DictWriter(csvFp, fieldnames=gInvalidSentenceCsvHeaders) csvDictWriter.writerow(rowDict) </code>
结果出错:
<code> File "/Users/crifan/dev/xxx/processData/mysqlQa/mongoDialogToMysqlQa.py", line 295, in insertDialog saveInvalidSentence(mongoId, invalidSentence, invalidReason) File "/Users/crifan/dev/dev_root/xxx/processData/mysqlQa/mongoDialogToMysqlQa.py", line 237, in saveInvalidSentence csvListWriter.writerow(rowValueList) File "/Users/crifan/.virtualenvs/xx-gXiJ4vtz/bin/../lib/python3.6/codecs.py", line 720, in write return self.writer.write(data) File "/Users/crifan/.virtualenvs/xx-gXiJ4vtz/bin/../lib/python3.6/codecs.py", line 377, in write self.stream.write(data) io.UnsupportedOperation: write </code>
python csv codes io.UnsupportedOperation: write
Python: Can not write to CSV file – Stack Overflow
io.UnsupportedOperation: not readable
io.UnsupportedOperation: not readable
python – IO.UnsupportedOperation: Not Writable –
python csv codecs io.UnsupportedOperation: write
utf 8 – Python error “io.UnsupportedOperation: write” when writing UTF-8 Characters – Stack Overflow
去改为w:
<code>with codecs.open(gCurInvalidSentenceFullFilename, "w", encoding="utf-8") as csvFp: </code>
结果即可。
【总结】
此处Python中用codecs去open文件,但是write出错:
io.UnsupportedOperation: write
原因是不小心是设置了r的mode:
<code> with codecs.open(gCurInvalidSentenceFullFilename, "r", encoding="utf-8") as csvFp: </code>
改为w:
<code> with codecs.open(gCurInvalidSentenceFullFilename, "w", encoding="utf-8") as csvFp: </code>
即可。
转载请注明:在路上 » 【已解决】python中用codecs去写入csv出错:io.UnsupportedOperation: write