Python中的否定

Dav*_*der 137 python negation

我正在尝试创建一个目录,如果路径不存在,但是!(不)运算符不起作用.我不确定如何在Python中否定...这样做的正确方法是什么?

if (!os.path.exists("/usr/share/sounds/blues")):
        proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
        proc.wait()
Run Code Online (Sandbox Code Playgroud)

Kar*_*oll 198

Python中的否定运算符是not.因此,只需更换你!not.

为您的示例,请执行以下操作:

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

对于您的具体示例(如Neil在评论中所述),您不必使用该subprocess模块,您只需使用os.mkdir()获得所需的结果,并添加异常处理优点.

例:

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.
Run Code Online (Sandbox Code Playgroud)


Cat*_*lus 28

Python喜欢英文关键字到标点符号.使用not x,即not os.path.exists(...).同样的事情会&&||它们andorPython编写的.


msh*_*ren 12

试着改为:

if not os.path.exists(pathName):
    do this
Run Code Online (Sandbox Code Playgroud)