Python中的否定

212 投票
4 回答
389937 浏览
提问于 2025-04-16 18:16

我想在路径不存在的时候创建一个目录,但是我发现“!”这个符号(表示“不”)在这里不管用。我不太确定在Python里怎么表示“不是”这个意思……那正确的做法是什么呢?

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

4 个回答

15

可以试试这个:

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

在Python中,使用英文关键词比用标点符号更好。比如说,应该用 not x,也就是 not os.path.exists(...)。同样的,&&|| 在Python中分别是 andor

291

在Python中,否定运算符是 not。所以只需要把你的 ! 替换成 not 就可以了。

对于你的例子,可以这样做:

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.

撰写回答