Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I have read that when a file is opened using the below format

with open(filename) as f: 

#My Code 

f.close()

explicit closing of file is not required. Can someone explain why is it so? Also if someone does explicitly close the file, will it have any undesirable effect?

1 Answer

0 votes
by (106k points)

 To open and close a file in Python you leave the nested block, Python automatically calls f.close() for you.

It doesn't matter whether you leave by just falling off the bottom, or calling break/continue/return to jump out of it, or raise an exception; no matter how you leave that block. It always knows you're leaving, so it always closes the file.*

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 24, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Oct 14, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
asked Aug 23, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 22, 2019 in Python by Vishal (106k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...