2024-04-26 07:51:57 发布
网友
我手工创建了一个名为InputData的文件夹。但我想在InputData文件夹中自动创建一个文件夹。我想知道操作系统路径存在在下面的代码中。在
`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异常:
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)
对您来说,
os.path.exists
的使用是多余的,因为如果目标目录/文件已经存在,您只需从os.mkdir
捕获FileExistsError
异常:如果您曾经运行过此代码块的多个线程或进程,它也有助于消除竞争条件的可能性。在
相关问题 更多 >
编程相关推荐