最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】python中用codecs去写入csv出错:io.UnsupportedOperation: write

Python crifan 6342浏览 0评论

折腾:

【已解决】Python中创建和保存数据到csv文件中

期间,用代码:

<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

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.191 seconds, using 22.06MB memory