Python中的否定 [英] Negation in Python

查看:395
本文介绍了Python中的否定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a directory if the path doesn't exist, but the ! (not) operator doesn't work. I'm not sure how to negate in Python... What's the correct way to do this?

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

推荐答案

Python中的求反运算符为not.因此,只需将!替换为not.

The negation operator in Python is not. Therefore just replace your ! with not.

以您的示例为例,

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


对于您的特定示例(如Neil在评论中所述),您不必使用subprocess模块,只需使用


For your specific example (as Neil said in the comments), you don't have to use the subprocess module, you can simply use os.mkdir() to get the result you need, with added exception handling goodness.

示例:

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.

这篇关于Python中的否定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆