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

Python (197) 2023-07-11 16:07:37

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

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

相关推荐:《Python入门教程》

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

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

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

发表回复