Python:无法写入CSV文件

4

我有这段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 <module>
    analyse("mydata.csv", "mynewdata.csv")
  File "main.py", line 25, in analyse
    writer.writerow(row)
io.UnsupportedOperation: not writable

我到底做错了什么? 我在64位的Windows 7上操作。
1个回答

12

你需要以写入模式打开文件:

openedCSvFileToWrite = open(csvFileToWrite, "w")

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


谢谢,这个方法可行,我完全没想到。我真的应该被踩一下。 - Amani
3
@Amani:这是一个正确的问题。如果每个人都理解一切,那么StackOverflow就不存在了 ;) 翻译:这是一个正确的问题。如果每个人都了解所有内容,那么就没有 StackOverflow 了 ;) - pepr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接