Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams with open('v.csv', 'w') as csvfile: cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) for w, c in p.items(): cwriter.writerow(w + c)

Here, p is a dictionary, w and c both are strings.

When I try to write to the file it reports the error:

ValueError: I/O operation on closed file.
with open('v.csv', 'w') as csvfile:
    cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for w, c in p.items():
        cwriter.writerow(w + c)

Outside the with block, the file is closed.

>>> with open('/tmp/1', 'w') as f:
...     print(f.closed)
False
>>> print(f.closed)

I also have the same problem. Here is my previous code

csvUsers = open('/content/gdrive/MyDrive/Ada/Users.csv', 'a', newline='', encoding='utf8')
usersWriter = csv.writer(csvUsers)
for t in users:
    NodeWriter=.writerow(users)
csvUsers.close() 

Apparently, I shoud write the usersWriter instead of NodeWriter.

NodeWriter=.writerow(users)
usersWriter=.writerow(users)

Below is my current code and it is working

csvUsers = open('/content/gdrive/MyDrive/Ada/Users.csv', 'a', newline='', encoding='utf8')
usersWriter = csv.writer(csvUsers)
for t in users:
    usersWriter=.writerow(users)
csvUsers.close() 
                Isn't NodeWriter=.writerow(users) a syntax error? =. is not in any Python grammar, is it?
– Robin De Schepper
                Jan 19 at 11:33

I had this problem when I was using an undefined variable inside the with open(...) as f:. I removed (or I defined outside) the undefined variable and the problem disappeared.

Another possible cause is the case when, after a round of copypasta, you end up reading two files and assign the same name to the two file handles, like the below. Note the nested with open statement.

with open(file1, "a+") as f:
    # something...
    with open(file2, "a+", f):
        # now file2's handle is called f!
    # attempting to write to file1
    f.write("blah") # error!!

The fix would then be to assign different variable names to the two file handles, e.g. f1 and f2 instead of both f.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.