如果路径不存在,我正在尝试创建一个目录,但是!(not) 运算符不起作用。我不确定如何在 Python 中否定......这样做的正确方法是什么?
if (!os.path.exists("/usr/share/sounds/blues")):
proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
proc.wait()
Python 中的否定运算符是not
. 因此,只需将您的替换!
为not
.
对于您的示例,请执行以下操作:
if not os.path.exists("/usr/share/sounds/blues") :
proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
proc.wait()
对于您的具体示例(正如尼尔在评论中所说),您不必使用该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.
Python 更喜欢英文关键字而不是标点符号。使用not x
,即not os.path.exists(...)
。同样的事情也适用于 Python中的&&
and ||
which are and
and 。or
改为尝试:
if not os.path.exists(pathName):
do this
结合其他人的输入(不使用,不使用括号,使用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)