Reputation: 109
When my program crashes with opened files what happens to them, are they automatically closed?
I'm aware the correct way is to use with
but I'm curious what will happen when I don't.
f = open('sample.txt', 'r')
# Example code that crashes the problem
a = 5 / 0
compared to
with open('sample.txt', 'r') as f:
a = 5 / 0
If the opened files are automatically closed when the program crashes what is the benefit of using the with
syntax?
Thank you in advance!
Upvotes: 1
Views: 1333
Reputation: 3907
Using with
closes the file automatically. Not using with
and not explicitly closing your file means that as long as your application is running it will leave the file open.
If your program crashes the file will be released and the lock will expire. Regardless of with. If your program hangs however, and you did not leave the with
statement, or simply used open, then you will keep the file open as long as your application is hung.
Upvotes: 2