我试图创建一个目录,如果路径不存在,但!(不是)运算符不工作。我不知道如何在Python中求反…正确的做法是什么?
if (!os.path.exists("/usr/share/sounds/blues")): proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"]) proc.wait()
Python更喜欢英语关键字而不是标点符号。使用not x,即not os.path.exists(...)。同样的事情也适用于&&和||,它们在Python中是and和or。
not x
not os.path.exists(...)
&&
||
and
or
试一试:
if not os.path.exists(pathName): do this
Python中的否定运算符是not。因此,只需将你的!替换为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()来获得你需要的结果,并添加了异常处理功能。
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),你会得到…
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)