简体   繁体   中英

How to save multiple files in Python?

So, I wrote this sript, which takes command line arguments and generates images based on them (there is only one argument now), it works prety good until it gets to the save function, I don't know why but it just takes the last image and saves it 10 times instead of saving every image

Here is the code;

import os, argparse
from PIL import Image as image
from PIL import ImageDraw as image_draw
from PIL import ImageFont as image_font

parser = argparse.ArgumentParser(description='Image generator')

#Argument definition

parser.add_argument('-num', action='store_true', required=False, help='Generates numbers')

numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

args = parser.parse_args()

arg_num = args.num

def img_gen(n, lenght):
    text = n

    fnts = 20

    fnt = image_font.truetype('Roboto.ttf', size=fnts, index=0, encoding='', layout_engine=None)
    gen_i_width = (6 * fnts)
    gen_i_height = (3 * fnts)

    gen_img = image.new('RGBA', (gen_i_width, gen_i_height), color=(0, 0, 0, 255))

    gen_text = image_draw.Draw(gen_img)
    gen_text.text((0,0), text, font=fnt, fill=(255, 255, 255, 255))
    text_size = gen_text.textsize(text, font=fnt, spacing=0, direction=None, features=None)

    text_s_list = list(text_size)
    text_width, text_height = text_s_list

    img_c = gen_img.crop((0, 0, text_width, text_height))

    for file_name in range(1, lenght + 1):
        img_c.save(f"{file_name:04d}.png")

def main():
    if arg_num == True:
        lenght = len(numbers)
        for n in numbers:
            img_gen(n, lenght)

if __name__ == '__main__':
    main()

Each time you create an image, you save it to multiple files with sequential numbers for names. This overwrites the previous image each time, in all the files.

Remove the loop from your img_gen function. Instead, save to one file with its name generated from n . Then each image will be saved into one file, and the file name will be the image number.

So, change

for file_name in range(1, lenght + 1):
    img_c.save(f"{file_name:04d}.png")

... to...

fnum = int(n)
img_c.save(f"{fnum:04d}.png")

I do something similar for some work

for i in list:
     #GRAPH
     plt.savefig("path/{0}/{1}.pdf".format(i,i));

This is saving to a folder with the name 'i' and the file name will be 'i.pdf'

When you have the following:

'{0}_{1}'.format('apple','juice')

the output is

'apple_juice'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM