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 个回答
-
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.