工作操作系统路径存在命令

2024-04-26 07:51:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我手工创建了一个名为InputData的文件夹。但我想在InputData文件夹中自动创建一个文件夹。我想知道操作系统路径存在在下面的代码中。在

`list =[1.0,2.0]
for hc in list:
    if not os.path.exists('InputData/'+str(hc)):
        os.mkdir('InputData/'+str(hc))`

Tags: path代码inhc路径文件夹forif
2条回答

对您来说,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)

相关问题 更多 >