我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
当前回答
最快的安全方式是:如果不存在,它会创造,如果不存在,它会消失:
from pathlib import Path
Path("path/with/childs/.../").mkdir(parents=True, exist_ok=True)
其他回答
试试 os.path.exist 函数
if not os.path.exists(dir):
os.mkdir(dir)
使用此命令检查并创建 dir
if not os.path.isdir(test_img_dir):
os.mkdir(test_img_dir)
最快的安全方式是:如果不存在,它会创造,如果不存在,它会消失:
from pathlib import Path
Path("path/with/childs/.../").mkdir(parents=True, exist_ok=True)
在您的程序/项目的输入点上拨打 Create_dir() 函数。
import os
def create_dir(directory):
if not os.path.exists(directory):
print('Creating Directory '+directory)
os.makedirs(directory)
create_dir('Project directory')
查看 os.makedirs: (它确保完整的路径存在) 要处理可能存在的目录的事实,查找 OSError. (如果存在_ok 是假的(默认情况下),如果目标目录已经存在,则会升起 OSError。
import os
try:
os.makedirs('./path/to/somewhere')
except OSError:
pass