Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creation and validation of directory using try/except or if else? [duplicate]

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.

like image 488
thclpr Avatar asked Jan 13 '14 15:01

thclpr


People also ask

Is try except faster than if?

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.

How do you create directory in Python if it does not exist?

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 .

How can I safely create a nested directory?

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.

How do you create a new directory in Python working directory?

makedirs() os. makedirs() method in Python is used to create a directory recursively.


1 Answers

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) 
like image 176
Dmitry Vakhrushev Avatar answered Oct 02 '22 23:10

Dmitry Vakhrushev