Someone recently said to me "In Python it is better to try and ask for forgiveness later instead of begging for permission" which I found quite funny but also relates to my question
I'm creating a personal assistant of sorts called Ada and was being pedantic about performance. From what I gather, using a try statement is faster when it works then checking and then executing. E.G: (The second one being slower if the directory DOESNT EXIST???)
import os
try:
os.makedirs("Test")
except FileExistsError:
pass
# VS
if not os.path.exists("Test"):
os.makedirs("Test")
So when creating coding, you need to weigh up whats more likely. In my example it would be the file is more likely to NOT exist so I should use a try block which yields better performance then an If-Else
I was wondering if this is of any benefit to try (pun intended) this method of the default If-Else?
P.S (This question isn't a duplicate of Python if vs try-except since that's not specifying about comparing the probabilities of the try:
code block)
My current code if anyone's interested: (Created a folder in AppData called Ada where a Config.ini file is made)
import os
AppDataDirectory = os.getenv("AppData")
AdaDirectory = AppDataDirectory + "\Ada"
ConfigFile = AdaDirectory + "\CONFIG.ini"
try:
File = open(ConfigFile, "r")
except FileNotFoundError:
try:
os.makedirs(AdaDirectory)
except FileExistsError:
print("Config File Missing")
# Setup Config File