182

I'm trying to create a directory if the path doesn't exist, but the ! (not) operator doesn't work. I'm not sure how to negate in Python... What's the correct way to do this?

if (!os.path.exists("/usr/share/sounds/blues")):
        proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
        proc.wait()
David Mulder
  • 6,276
  • 10
  • 40
  • 59
  • 19
    By the way, why not use Python's `os.mkdir()`? – Neil May 24 '11 at 22:51
  • 1
    I wasn't aware of the os.mkdir() function, although I figured there was something like that. – David Mulder May 25 '11 at 19:41
  • It's better here to just `try: os.mkdir(path)` and handle the error. If you check first ('look before you leap') someone else can create or delete that folder after your check (but before you create it), and there could still be an error. The check doesn't guarantee anything at the time of creation. This idea is sometimes called ['easier to ask forgiveness than permission'](https://docs.python.org/3/glossary.html#term-eafp). Even better (but even more specific to this problem), you can do `os.makedirs(path, exist_ok=True)` to create the path and ignore a `FileExistsError`. – speedstyle Sep 11 '20 at 21:50

4 Answers4

249

The negation operator in Python is not. Therefore just replace your ! with not.

For your example, do this:

if not os.path.exists("/usr/share/sounds/blues") :
    proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
    proc.wait()

For your specific example (as Neil said in the comments), you don't have to use the subprocess module, you can simply use os.mkdir() to get the result you need, with added exception handling goodness.

Example:

blues_sounds_path = "/usr/share/sounds/blues"
if not os.path.exists(blues_sounds_path):
    try:
        os.mkdir(blues_sounds_path)
    except OSError:
        # Handle the case where the directory could not be created.
Karl Nicoll
  • 14,491
  • 3
  • 46
  • 60
36

Python prefers English keywords to punctuation. Use not x, i.e. not os.path.exists(...). The same thing goes for && and || which are and and or in Python.

Cat Plus Plus
  • 113,388
  • 26
  • 185
  • 215
15

try instead:

if not os.path.exists(pathName):
    do this
mshell_lauren
  • 4,713
  • 3
  • 27
  • 36
1

Combining the input from everyone else (use not, no parens, use os.mkdir) you'd get...

special_path_for_john = "/usr/share/sounds/blues"
if not os.path.exists(special_path_for_john):
    os.mkdir(special_path_for_john)
Community
  • 1
  • 1
chmullig
  • 12,106
  • 5
  • 32
  • 52
  • 1
    Your code (and the OP's) is an accident waiting to happen -- two instances of a longish literal string that presumably should be identical. And please don't retort that it's just an example -- it's a BAD example for newbies. – John Machin May 24 '11 at 23:01