5

I have this snippet of Python code:

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")

when run using Python 3.4 I get the following error message:

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

What Am I doing wrong? I'm on Windows 7 64bit.

1 Answer 1

13

You have to open the file in write mode:

openedCSvFileToWrite = open(csvFileToWrite, "w")

Note that in Python 2.x, the docs always use 'wb', rather than 'w'.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks worked, I totally never thought of that. I really deserve a down vote.
@Amani: This is a correct question. If everyone understood everything, there would be no StackOverflow ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.