Python中的否定

问题:Python中的否定

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

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

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()

回答 0

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.

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

For your example, do this:

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

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.

Example:

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.

回答 1

Python更喜欢英文关键字而不是标点符号。使用not x,即not os.path.exists(...)。同样的事情会&&||它们andorPython编写的。

Python prefers English keywords to punctuation. Use not x, i.e. not os.path.exists(...). The same thing goes for && and || which are and and or in Python.


回答 2

请尝试:

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

try instead:

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

回答 3

结合其他人的输入(不要使用,不要使用括号,使用os.mkdir),您会得到…

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

Combining the input from everyone else (use not, no parens, use os.mkdir) you’d get…

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