Python:无法写入CSV文件

 刘哥2502908157 发布于 2023-01-06 23:23

我有这段Python代码:

import csv

def analyse(csvFileToRead, csvFileToWrite):
    # open file to read
    openedCsvFileToRead = open(csvFileToRead)
    reader = csv.reader(openedCsvFileToRead)

    # open file to write
    openedCsvFileToWrite = open(csvFileToWrite)
    writer = csv.writer(openedCsvFileToWrite)

    for row in reader:
        date = row[8]
        if date[0] == "5":
            writer.writerow(row)

    # close file
    openedCsvFileToRead.close()
    openedCsvFileToWrite.close()

if __name__ == "__main__":
    analyse("mydata.csv", "mynewdata.csv")

当使用Python 3.4运行时,我收到以下错误消息:

Traceback (most recent call last):
  File "main.py", line 40, in 
    analyse("mydata.csv", "mynewdata.csv")
  File "main.py", line 25, in analyse
    writer.writerow(row)
io.UnsupportedOperation: not writable

我究竟做错了什么?我在Windows 7 64bit上.

1 个回答
  • 您必须以写入模式打开文件:

    openedCSvFileToWrite = open(csvFileToWrite, "w")
    

    请注意,在Python 2.x中,文档始终使用'wb',而不是'w'.

    2023-01-06 23:38 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有