python - 获取每个输出文件的唯一名称 (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']))
如果你需要,你可以在这里找到完整的代码
解决方案
使用枚举:
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))
推荐阅读
- elasticsearch - Security-exception-action-[indices:admin/settings/update] 在索引 [apm-7.6.0-error-000001] 上的用户 [kibana] 未经授权
- parquet - 从 Teiid 访问 Parquet 文件
- flutter - 颤振动画 CrossAxisalignment 与补间
- python - 处理括号的正则表达式
- arrays - 如何在 C 中制作包含不同数据类型的动态多维数组?
- python - 重新排序 django 核心功能
- android - 在 Flutter 中的 ListView 中搜索(使用 Firebase 中的数据)
- hyperledger-fabric - Hyperledger Fabric 2.2 - 使用 collection-config 保护私有数据
- php - 我如何从php中的对象中获取值
- sql-server - Azure ADF 在查找活动中使用 concat 构建查询