How this file can be closed. Any idea?
with open('output.txt','w', encoding='UTF-8') as output:
output.writelines(str(i)+'\n' for i in range(5))
How this file can be closed. Any idea?
with open('output.txt','w', encoding='UTF-8') as output:
output.writelines(str(i)+'\n' for i in range(5))
The file is automatically closed when you leave the "with
-block" or an exception is encountered. This is why it's the preferred way to open files.
See this PEP 343 -- The "with" Statement for more information on the with
statement. The Python “with” Statement by Example gives more information.
UPDATE:
Your inability to delete a file opened with with
was due to the file having been left open previously (when not using with
and not explicitly close
ing it). As a test using a different file and with
didn't create a problem.
http://effbot.org/zone/python-with-statement.htm
To paraphrase:
In Python 2.5, the file object has been equipped with enter and exit methods; the former simply returns the file object itself, and the latter closes the file.
So the with statement's "teardown" action is to actually close the file automatically.
with
statement automatically closes file for you.
read more here: http://preshing.com/20110920/the-python-with-statement-by-example