簡體   English   中英

Python:無法寫入CSV文件

[英]Python: Can not write to CSV file

我有以下這段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

我究竟做錯了什么? 我在Windows 7 64位上。

您必須以寫入模式打開文件:

openedCSvFileToWrite = open(csvFileToWrite, "w")

請注意,在Python 2.x中, 文檔始終使用'wb'而不是'w'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM