Negation in Python

PythonNegation

Python Problem Overview


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()

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

try instead:

if not os.path.exists(pathName):
    do this

Solution 4 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid MulderView Question on Stackoverflow
Solution 1 - PythonKarl NicollView Answer on Stackoverflow
Solution 2 - PythonCat Plus PlusView Answer on Stackoverflow
Solution 3 - Pythonmshell_laurenView Answer on Stackoverflow
Solution 4 - PythonchmulligView Answer on Stackoverflow