+ 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()

29th Dec 2020, 5:33 PM
Ratnapal Shende
Ratnapal Shende - avatar
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.
29th Dec 2020, 5:36 PM
A͢J
A͢J - avatar
+ 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.
29th Dec 2020, 11:29 PM
David Carroll
David Carroll - avatar
+ 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.
29th Dec 2020, 11:26 PM
David Carroll
David Carroll - avatar
+ 4
Ratnapal Shende If they gives this functionality to open() then how you will decide which file should be open?
29th Dec 2020, 5:52 PM
A͢J
A͢J - avatar
+ 2
Ratnapal Shende Suppose I am not using open() like close(). Now tell me how you will open your file?
29th Dec 2020, 6:52 PM
A͢J
A͢J - avatar
+ 2
Ratnapal Shende But I am not using it as you asked why it's not like close().
29th Dec 2020, 7:05 PM
A͢J
A͢J - avatar
+ 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()
29th Dec 2020, 7:13 PM
Ratnapal Shende
Ratnapal Shende - avatar
+ 1
I Am Groot ! then why they don't give that functionality in open() itself ??
29th Dec 2020, 5:42 PM
Ratnapal Shende
Ratnapal Shende - avatar
+ 1
I Am Groot ! sorry but will you please explain more? I didn't understand...
29th Dec 2020, 6:16 PM
Ratnapal Shende
Ratnapal Shende - avatar
+ 1
That's one of the questions I've had, that i forgot about asking. Good one.
31st Dec 2020, 4:54 PM
Tenupz
0
I Am Groot ! using with open() as fp: ??
29th Dec 2020, 7:03 PM
Ratnapal Shende
Ratnapal Shende - avatar