我手动创建了一个名为InputData的文件夹。但是我想在输入数据文件夹中自动创建一个文件夹。我想知道os.path.exist在以下代码中的重要性。
`list =[1.0,2.0]
for hc in list:
if not os.path.exists('InputData/'+str(hc)):
os.mkdir('InputData/'+str(hc))`
使用os.path.exists
对于您的目的来说是多余的,因为如果目标目录/文件已经存在,您只需从os.mkdir
中捕获FileExistsError
异常:
for hc in list:
try:
os.mkdir('InputData/'+str(hc))
except FileExistsError:
pass
如果您曾经运行过此代码块的多个线程或进程,这也将有助于消除竞争条件的可能性。
#!/usr/bin/python3.6
import os
list =[1.0,2.0]
for hc in list:
if not os.path.exists('InputData/'+str(hc)):
os.makedirs('InputData/'+str(hc),exist_ok=True)