198

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

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

4 回答 4

264

Python 中的否定运算符是not. 因此,只需将您的替换!not.

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

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

对于您的具体示例(正如尼尔在评论中所说),您不必使用该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.
于 2011-05-24T22:41:50.727 回答
37

Python 更喜欢英文关键字而不是标点符号。使用not x,即not os.path.exists(...)。同样的事情也适用于 Python中的&&and ||which are andand 。or

于 2011-05-24T22:41:34.253 回答
15

改为尝试:

if not os.path.exists(pathName):
    do this
于 2011-05-24T22:41:46.757 回答
2

结合其他人的输入(不使用,不使用括号,使用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)
于 2011-05-24T22:55:58.333 回答