我试图创建一个目录,如果路径不存在,但!(不是)运算符不工作。我不知道如何在Python中求反…正确的做法是什么?

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

Python更喜欢英语关键字而不是标点符号。使用not x,即not os.path.exists(…)。Python中的&&和||也是如此,它们是and和or。


试一试:

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

Python中的否定运算符不是。所以就换掉你的吧!不。

在你的例子中,这样做:

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

对于您的特定示例(如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.

结合其他所有人的输入(使用not,不使用parens,使用os.mkdir),你会得到…

special_path_for_john = "/usr/share/sounds/blues"
if not os.path.exists(special_path_for_john):
    os.mkdir(special_path_for_john)