This is only a question regarding which one would be more "pythonic"
using if:
import os
somepath = 'c:\\somedir'
filepath = '%s\\thefile.txt' % somepath
if not os.path.exists(somepath) and not os.path.isfile(filepath):
os.makedirs(somepath)
open(filepath, 'a').close
else:
print "file and dir allready exists"
or using try/Except:
import os
somepath = 'c:\\somedir'
filepath = '%s\\thefile.txt' % somepath
try:
os.makedirs(somepath)
except:
print "dir allready exists"
try:
with open(filepath):
// do something
except:
print "file doens't exist"
As you can see on the examples above, which one would be more correct on python? Also, On which cases should i use try/except instead if/else ? I mean, should i replace all my if/else tests to try/except?
Thanks in advance.
Now it is clearly seen that the exception handler ( try/except) is comparatively faster than the explicit if condition until it met with an exception. That means If any exception throws, the exception handler took more time than if version of the code.
Method 2: Using isdir() and makedirs() In this method, we will use isdir() method takes path of demo_folder2 as an argument and returns true if the directory exists and return false if the directory doesn't exist and makedirs() method is used to create demo_folder2 directory recursively .
The most common methods to safely create Python Nested Directories are by using the Python pathlib library and the os library module. Before you can work with files in Python, we must compulsorily import these modules into our program.
makedirs() os. makedirs() method in Python is used to create a directory recursively.
The second one is more pythonic: "Easier to ask for forgiveness than permission."
But there is another benefit of using exceptions in your particular case. If your application runs multiple processes or threads "asking permissions" doesn't guarantee consistency. For example following code runs well in single thread, but may be crashed in multiple ones:
if not os.path.exists(somepath):
# if here current thread is stopped and the same dir is created in other thread
# the next line will raise an exception
os.makedirs(somepath)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With