首页 > 解决方案 > 获取每个输出文件的唯一名称 (docxtpl)

问题描述

所以,我有一个基于 docxtpl 的模板。它基于自动形成的 csv 表制作文件。问题是 - 有时我必须创建 2-3 个相同的文件,其中所有差异都在一个参数中,因此,我需要每个文件的唯一名称。但我不太明白,如何在文件名中添加计数器?

我在模板定义中添加了一个计数器,但并不真正了解如何将其包含到文件名中(它是doc.save部分)

doc.render(context)

def create_counter():
    i = 1

    def func():
        nonlocal i
        i += 2
        return i

    return func

counter = create_counter()

doc.save(output_path / output_str.format(short_name=student['short_name']))

如果你需要,你可以在这里找到完整的代码

标签: python

解决方案


使用枚举

def templater(templat e_path, students):
    for i, student in enumerate(students):
        doc = DocxTemplate(template_path)

        student = middle_processor(student)
        context = {
            'first_name': student['first_name'],
            'second_name': student['second_name'],
            'third_name': student['third_name'],
            'year_number': student['year_number'],
            'course_name': student['course_name'],
            'number': student['number'],
            'form_of_education': student['form_of_education'],
            'count': student['count'],
            # 'where_is': student['where_is'],

        }

        doc.render(context)

        doc.save(output_path / output_str.format(short_name=student['short_name'], counter=i))

推荐阅读