Skip to content
Advertisement

Can’t write to CSV in function

This will return the exception “ValueError: I/O operation on closed file”

JavaScript

I notice that when I put all the code under the initial CSV Open everything works fine, it just dosen’t work when put into a function.

JavaScript

Advertisement

Answer

It doesn’t work, because you did not put all of the pertinent code into the function. You open the file in a with block inside your function. Then you exit the block (which closes the file), return from the function, and then your main program attempts to write to the closed file … hence the error message.

If you want to open the file in the function, but write to it in the calling routine, then you need a normal open, and have the function return the needed information. For instance:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement