如何在不同目录的python中保存图像?

时间:2019-04-12 16:15:00

标签: python image save

此代码使图像循环播放。我想将每个图像保存在其自己的目录中。例如,我想将img1放在img1文件夹中,将img2放在img2文件夹中,依此类推。我想在循环中使用索引作为后缀。

 img = makeImage(g2_value,width=512)
        with open('%d.png' % i, 'wb') as f:
            f.write(img)

2 个答案:

答案 0 :(得分:0)

使用os.mkdir创建目录。然后将图像写入正确的路径。

https://docs.python.org/2/library/os.html#os.mkdir

os.mkdir(str(i))
with open('%d/%d.png' % (i,i), 'wb') as f:
    f.write(img)

答案 1 :(得分:0)

您最好的选择是编写一个函数,该函数接受fn作为输入saveImg(fn, ...)作为示例,然后创建一个不存在的文件夹。请非常小心,因为您可能会覆盖以前的工作。

import os
if os.path.exists("data") is False:
    os.mkdir("data")

fldr_template = "data/img{}"

for i in range(10):
    fldr = fldr_template.format(i)
    if os.path.exists(fldr) is False:
        os.mkdir(fldr)
    fn = "data/img{}/img{0}.png".format(i)
    # here you write your file to fn
    saveImg(fn, ...)