File Methods
close()
Flush and close the open file handle.
file.close()
file.close() flushes any unwritten buffered data to the operating system and closes the file descriptor.
Once closed, any further read or write operations on the file object raise a ValueError.
Returns
None.
Try it
Run it and change it
import tempfile
with tempfile.NamedTemporaryFile(mode='w+', delete=True) as f:
f.write('testing')
print('Closed before:', f.closed)
f.close()
print('Closed after:', f.closed)Worth knowing
- Automatic closing with context managers: Using
with open(...) as f:ensuresclose()is called automatically, even if an exception occurs.