Python中的否定

我试图创建一个目录,如果路径不存在,但!(不是)运算符不工作。我不知道如何在Python中求反…正确的做法是什么?

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

Python更喜欢英语关键字而不是标点符号。使用not x,即not os.path.exists(...)。同样的事情也适用于&&||,它们在Python中是andor

试一试:

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

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.

结合其他所有人的输入(使用not, no parens,使用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)