2

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??

Jon Surrell
  • 9,444
  • 8
  • 48
  • 54
Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
  • 1
    Aside: You are probably better off with `if os.path.isdir(...)` rather than `if os.path.exists(...)`. Your code will have unexpected results if intended directory name already exists as a regular file. – Robᵩ Jun 25 '15 at 14:22

2 Answers2

6

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.

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
  • For some reason, passing the access mode as a parameter to `makedirs` did not take effect. The directory was creed, but not with the desired mode. I added a following `os.chmod(args.outputDirectory, 0o666)` and that worked just fine (Python 3.2). – Mawg says reinstate Monica Jun 25 '15 at 14:25
3

You don't need to call os.path.exists() (or os.path.isdir()); os.makedirs() has exist_ok parameter.

And as @Thomas Orozco mentioned, you shouldn't check os.makedirs()' return value because os.makedirs() indicates errors by raising an exception instead:

try:
    os.makedirs(args.output_dir, mode=0o666, exist_ok=True)
except OSError as e:
    sys.exit("Can't create {dir}: {err}".format(dir=output_dir, err=e))

Note: Unlike os.path.exist()-based solution; it raises an error if the path exists but it is not a directory (or a symlink to a directory).

There could be issues with the mode parameter, see the note for versions of Python before 3.4.1

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670