Reputation: 39
I'm attempting to make a part of a class that will allow me to create a new directory for output files each time an instance is created. However, whenever the mkdir_p function is executed I get this error:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
jim = OPNprobe('oops','x','a')
File "H:/Bio_Files/Pyscripts/opsinomics/aa.pya.py", line 22, in __init__
self.mkdir_p(self.path+'\\'+self.out_name)
Empty
I only get this error if the directory hasn't been created already. Once it throws the error and creates the directory, it will then let me initiate a new instance without thowing the error again.
Here's the function I'm using to create the new directory. I'm passing the path variable from the initial variables supplied by the user. the 'path' variable is currently just 'oops', so nothing fancy and should just create a directory named oops.
def mkdir_p(self,path):
try:
os.makedirs(self.path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST:
pass
else: raise
Any help would be much appreciated...just getting into writing classes and I'm struggling with how to juggle variables between functions and create output files without defining the file path within each function.
Upvotes: 0
Views: 301
Reputation: 7255
I think you want to write your mkdir_p
method like this:
def mkdir_p(self,path):
try:
os.makedirs(self.path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST:
pass
else: raise # pay attention here, this line must be indented the same as the 'if' line
In you original code, else
is a branch for try
and the code under else
branch will be executed regardless whether there is an exception or not.
Besides, you'd better use os.path.join(self.path, self.out_name)
instead of self.mkdir_p(self.path+'\\'+self.out_name)
, it will make your code more portable.
Upvotes: 1