Python中的否定

发布于 2021-01-29 19:12:13

如果路径不存在,我正在尝试创建目录,但是!(不是)运算符不起作用。我不确定如何在Python中取反…执行此操作的正确方法是什么?

if (!os.path.exists("/usr/share/sounds/blues")):
        proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
        proc.wait()
关注者
0
被浏览
53
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    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.
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看