自定义输出文件名

Customizing output file name

with open('media_cdn/account/pdf01.pdf', 'wb') as out_file:
        output.write(out_file)

如何将其格式化为每个输出具有自定义名称?比如我试过:

author_id=str(instance.author.id)

with open('media_cdn/account/{author_id}-pdf01.pdf', 'wb') as out_file:
    output.write(out_file)

然而,文件输出为"{author_id}-pdf01.pdf"

使用:

with open("media_cdn/account/{0}-pdf01.pdf".format(author_id), 'wb') as out_file:

代替

with open('media_cdn/account/{author_id}-pdf01.pdf', 'wb') as out_file:

'media_cdn/account/{author_id}-pdf01.pdf' 是一个字符串。此字符串的 {author_id} 部分不会被 author_id 变量本身替换。

你就不能这样做吗

author_id=str(instance.author.id)

with open(f'media_cdn/account/{author_id}-pdf01.pdf', 'wb') as out_file:
    output.write(out_file)