简体   繁体   English

如何在 Python 中保存多个文件?

[英]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所以,我写了这个脚本,它采用命令行 arguments 并基于它们生成图像(现在只有一个参数),它工作得很好,直到它保存 function,我不知道为什么,但它只需要最后一张图像并保存 10 次,而不是保存每张图像

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.从您的img_gen function 中删除循环。 Instead, save to one file with its name generated from n .相反,保存到一个文件,其名称是从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'这是保存到名为“i”的文件夹中,文件名为“i.pdf”

When you have the following:当您有以下情况时:

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

the output is output 是

'apple_juice'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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