Search code examples
pythonpython-3.xmkdirs

Python create directory failing


I am using some pretty standard code:

 1   if not os.path.exists(args.outputDirectory):
 2       if not os.makedirs(args.outputDirectory, 0o666):
 3           sys.exit('Fatal: output directory "' + args.outputDirectory + '" does not exist and cannot be created')

I remove the directory and the check at 1 drops through to 2. I one-step beyond that and hit the error message at 3.

However, when I check, the directory was created successfully.

drwxrwsr-x 2 userId userGroup  4096 Jun 25 16:07 output/

What am I missing??


Solution

  • os.makedirs does not indicate whether it succeeded through its return value: it always returns None.

    None is False-y, therefore, not os.makedirs(args.outputDirectory, 0o666) is always True, which triggers your sys.exit code path.


    Fortunately, you don't need any of that. If os.makedirs fails, it'll throw an OSError.

    You should catch the exception, not check the return value:

    try:
        if not os.path.exists(args.outputDirectory):
            os.makedirs(args.outputDirectory, 0o666):
    except OSError:
        sys.exit('Fatal: output directory "' + args.outputDirectory + '" does not exist and cannot be created')
    

    If no OSError is thrown, that means the directory was successfully created.