-2

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))
Levon
  • 138,105
  • 33
  • 200
  • 191
indiag
  • 233
  • 1
  • 4
  • 10

3 Answers3

7

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 closeing it). As a test using a different file and with didn't create a problem.

Levon
  • 138,105
  • 33
  • 200
  • 191
  • Yes but when i go to delete it, give me a message that it is still open in pythonw.exe – indiag Jun 19 '12 at 15:26
  • @indiag That should not happen .. perhaps the file is still open from a previous run when you didn't use `with` (I think I saw an earlier question from you, perhaps I'm wrong). It's hard to tell without seeing all of your code. In the meantime, I'd suggest using a different output file name e.g., `output2.txt` and see if you have the same problem just to help troubleshoot/pinpoint the issue. – Levon Jun 19 '12 at 15:29
  • How correct are you. Sorry for my mistake. I try 1 hour to understand. ohhhhhhhhhhh – indiag Jun 19 '12 at 15:32
  • 1
    Why the downvote? I'm happy to correct any error or improve the answer if I'm given some constructive feedback. Downvote **without** an explanation doesn't help OP, SO or me. – Levon Jun 19 '12 at 15:46
  • I didn't downvote, but the title did not fit the question, which was anyhow badly worded. Edit: I'm commenting on the downvote of the question, not the post given by @Levon – cdarke Jun 19 '12 at 16:05
  • @cdarke I think your comment should be directed at OP not me? I am trying to figure out why I got a downvote for my answer. – Levon Jun 19 '12 at 16:06
  • @cdarke Based on your comment I did edit OP's question title to reflect the true nature of the problem (though it's not reasonable to downvote me for OP's choice of words - if that was the reason - which is unknown) – Levon Jun 19 '12 at 16:14
3

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.

DeaconDesperado
  • 9,977
  • 9
  • 47
  • 77
2

with statement automatically closes file for you.

read more here: http://preshing.com/20110920/the-python-with-statement-by-example

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504