我正在尝试创建一个目录,如果路径不存在,但是!(不)运算符不起作用.我不确定如何在Python中否定...这样做的正确方法是什么?
if (!os.path.exists("/usr/share/sounds/blues")):
proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
proc.wait()
Run Code Online (Sandbox Code Playgroud)
Kar*_*oll 198
Python中的否定运算符是not.因此,只需更换你!的not.
为您的示例,请执行以下操作:
if not os.path.exists("/usr/share/sounds/blues") :
proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
proc.wait()
Run Code Online (Sandbox Code Playgroud)
对于您的具体示例(如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.
Run Code Online (Sandbox Code Playgroud)
msh*_*ren 12
试着改为:
if not os.path.exists(pathName):
do this
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
199156 次 |
| 最近记录: |