您的当前位置:首页正文

python如何判断图片路径是否存在

2024-08-01 来源:知网教育

1、在向文件夹中保存数据前,先判断该文件夹(路径)是否存在。

save_path = '/root/.../image/result'
if not os.path.exists(save_path):
    os.makedirs(save_path)

相关推荐:《》

本来路径里只有到image文件夹的,执行完后会自动在image下创建result文件夹。

2、在打开某些图片时,可以先判断该图片的路径是否存在。

if img == 'target7.jpg':
    img_path = os.path.join(dir_path, img)
    if imghdr.what(img_path):  # 判断是否能打开
        target_img = Image.open(img_path)
        target_img.save(os.path.join(root, 'trainB/{}_B.jpg'.format(count+6)))