我有这段 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 中,docs始终使用 'wb',而不是 'w'。
