+ 2
why we don't need to use close() if we use with open block : ?
#using with open we don't need to close() the file #why? with open("filename") as fp : fp.write("hello world!") #using just open() #why we need close() ❓ fp=open("filename") fp.write("hello world!") fp.close()
11 ответов
+ 16
Ratnapal Shende
Already given in lesson
"The file is automatically closed at the end of the with statement, even if exceptions occur within it."
That's why no need.
+ 6
Ratnapal Shende BTW... In your example:
----
try:
fp=open()
#do stuff
except:
fp.close()
finally:
fp.close()
----
You only need fp.close() in the finally block. The catch block should not contain clean up code.
+ 5
The with statement creates a new context behind the scenes that will call fs.__enter__() to get a reference to the object. This reference will be held in a separate runtime context so that it will be unaffected by any exceptions thrown in the main context.
Whether or not an unhandle exception occurs, the context manager will always call fs.__exit__(). This method will take care of calling obj.close() out of context which cleans everything thing up.
Take a look at my code where I created a Foo class to demonstrate how this would work in a very simple example.
https://code.sololearn.com/ca0a6a9a2a20/?ref=app
Apologies if the code is a bit too advanced for those in the early stages of learning. I wanted to go a little deeper in my review.
+ 4
Ratnapal Shende
If they gives this functionality to open() then how you will decide which file should be open?
+ 2
Ratnapal Shende
Suppose I am not using open() like close(). Now tell me how you will open your file?
+ 2
Ratnapal Shende But I am not using it as you asked why it's not like close().
+ 2
I Am Groot ! my brain is not working
please explain it to me in simple words...
why we need to use close() when we use open()?
also we need to use exception handling with it to make sure our file is closed properly...
why?
try:
fp=open()
#do stuff
except:
fp.close()
finally:
fp.close()
+ 1
I Am Groot ! then why they don't give that functionality in open() itself ??
+ 1
I Am Groot ! sorry but will you please explain more? I didn't understand...
+ 1
That's one of the questions I've had, that i forgot about asking. Good one.
0
I Am Groot ! using with open() as fp: ??