Reputation: 23
I'm trying to open a file in python and print a message when the file doesn't exist. But I'm confused whether to close the file or not when the exception happens.
try:
file = open(sys.argv[1], "r")
file.close() # should I do this?
except OSError:
print(f"{sys.argv[1]} file not found.")
Upvotes: 1
Views: 791
Reputation: 2425
A simpler method of checking if a file exists:
import os
if not os.path.exists(sys.argv[1]):
print(f"{sys.argv[1]} file not found.")
But to answer your question, the ```file.close()`` happens only when the file exists and you successfully open the file. Not when the exception occurs.
Edit: As pointed out by @ekhumoro, the above has a race condition (when other processes access that file). If no other process accesses that file, then the above code works.
Solution is as @ekhumoro pointed out is to use your original try/except method.
Upvotes: 1