What this error means
You tried to read from or write to a file object that has already been closed. Once a file is closed (either explicitly with .close() or automatically when exiting a with block), you can't perform operations on it.
Common causes
- You closed the file, then tried to use it again.
- You exited a
withblock, then tried to use the file outside it. - You're reusing a file variable that was closed earlier.
Example that causes the error
f = open('data.txt', 'r')
f.close()
content = f.read() # ValueError: file is closed
with open('data.txt', 'r') as f:
pass
content = f.read() # ValueError: file closed after with block
How to fix it: read before closing
Read or write all data before closing the file:
f = open('data.txt', 'r')
content = f.read() # OK: read before closing
f.close()
# Or use with statement:
with open('data.txt', 'r') as f:
content = f.read() # OK: read inside with block
# File auto-closes here, but content is already saved
Store data before closing
with open('data.txt', 'r') as f:
lines = f.readlines() # Read all lines first
# Now you can use lines even though file is closed
for line in lines:
print(line)
Reopen if needed
with open('data.txt', 'r') as f:
first = f.readline()
# Need more? Reopen:
with open('data.txt', 'r') as f:
second = f.readline()