我想在路径不存在时创建一个目录,但是! (非) 运算符不起作用。我不确定如何在Python中取反...应该如何正确地实现?
if (!os.path.exists("/usr/share/sounds/blues")):
proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
proc.wait()
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.
Python倾向于使用英文关键词而非标点符号。使用 not x
,即 not os.path.exists(...)
。对于&&
和||
也是同样的情况,它们在Python中分别为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)
os.mkdir()
函数? - Neiltry: os.mkdir(path)
并处理错误。如果您先进行检查(“先看后跳”),则在您进行检查之后,其他人可能会创建或删除该文件夹,并且仍然可能存在错误。检查不能保证在创建时有任何事情发生。这个想法有时被称为'容易寻求宽恕而不是许可'。更好的方法(但更具体地针对此问题)是使用os.makedirs(path,exist_ok = True)
来创建路径并忽略FileExistsError
。 - speedstyle