ValueError : I/O operation on closed file
Asked Answered
S

7

166
import csv    

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.
Sordello answered 23/9, 2013 at 6:8 Comment(0)
T
227

Indent correctly; your for statement should be inside the with block:

import csv    

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)
True
Telencephalon answered 23/9, 2013 at 6:9 Comment(0)
S
11

Same error can raise by mixing: tabs + spaces.

with open('/foo', 'w') as f:
 (spaces OR  tab) print f       <-- success
 (spaces AND tab) print f       <-- fail
Sadomasochism answered 26/3, 2018 at 21:43 Comment(1)
True, but this is always the case in python when mixing them up right?Inge
R
1

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() 
Rrhagia answered 24/6, 2022 at 3:19 Comment(1)
Isn't NodeWriter=.writerow(users) a syntax error? =. is not in any Python grammar, is it?Speechmaker
S
0
file = open("filename.txt", newline='')
for row in self.data:
    print(row)

Save data to a variable(file), so you need a with.

Sacramentalism answered 14/12, 2020 at 8:27 Comment(0)
I
0

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.

Inspire answered 26/2, 2021 at 16:27 Comment(0)
B
0

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.

Bibbye answered 9/1, 2022 at 20:59 Comment(0)
F
0

I ran into a similar problem after using auto-py-to-exe to compile my program.

I used with open(link, "rb") as f: but switching to PdfReader method fixed it.

Just wanted to share in case someone else faces this.

# it diesn't work --> ValueError: I/O operation on closed file.
     for link in links:
                if os.path.isfile(link):
                    with open(link, "rb") as f:
                    pdf_reader = PyPDF2.PdfReader(f)
            pdf_exporter.write("C:\\Temp\\test.pdf")
            os.startfile("C:\\Temp\\test.pdf")

# it does
     for link in links:
                if os.path.isfile(link):
                    # with open(link, "rb") as f:
                    # pdf_reader = PyPDF2.PdfReader(f)
                    pdf_reader = PyPDF2.PdfReader(link)
            pdf_exporter.write("C:\\Temp\\test.pdf")
            os.startfile("C:\\Temp\\test.pdf")
Feckless answered 29/8, 2023 at 15:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.