Here is the code:
def make_dir(dir_name): if os.path.exists(dir_name): shutil.rmtree(dir_name) try: os.makedirs(dir_name) except OSError, e: print "ErrorNo: %s (%s)" % (e.errno, errno.errorcode[e.errno]) raise
IFF, the directory already exists, I get the following:
ErrorNo: 13 (EACCES) Traceback (most recent call last): File "run_pnoise.py", line 167, in <module> make_dir("prep_dat") File "run_pnoise.py", line 88, in make_dir os.makedirs(dir_name) File "c:\Program Files (x86)\Python27\lib\os.py", line 157, in makedirs mkdir(name, mode) WindowsError: [Error 5] Access is denied: 'prep_dat'
If I run the program again, it works, indicating that the program really has access to directories, since the shutil.rmtree call works fine. I came up with a workaround that I will post. However, is there a better explanation and / or workaround?
My guess is that the shutil.rmtree call is returned before the OS completes the deletion of all files and subdirectories completely. Also, since the shutil.rmtree call does not throw an exception, any EACCESS (13) error in the makedirs call is probably fictitious. My attempt (modified after Apalala's comment):
def make_dir(dir_name): retry = True if os.path.exists(dir_name): shutil.rmtree(dir_name) while retry: try:
This seems to work reliably. Other posts have a race condition problem, however this seems unlikely and is likely to result in another exception.
source share