简体   繁体   English

在reportlab中保存变量文件名

[英]saving a variable filename in reportlab

I keep getting an error " no attribute for string .pdf" with my code. 我的代码不断出现错误“字符串.pdf没有属性”。 It works as a static filename, but not as a variable. 它可以用作静态文件名,但不能用作变量。 I have read the other examples on opening a filename, but none of them are inline like reportlab needs. 我已经阅读了有关打开文件名的其他示例,但是它们都不像reportlab需要那样内联。

    testid = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
    basename = str("cert")
    filename = "_".join([basename, testid])
    print filename
    canvas = canvas.Canvas(filename.pdf, pagesize=letter)

Here's a working example that fails on the last line, but should demonstrate the problem: 这是一个工作示例,在最后一行失败,但是应该演示该问题:

#!python2
#coding=utf-8

import datetime

testid = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
basename = str("cert")
filename = "_".join([basename, testid])
print filename
print "filename.pdf"
print filename.pdf

Output: 输出:

cert_170508_152300
filename.pdf
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print filename.pdf
AttributeError: 'str' object has no attribute 'pdf'

You are passing a non-existing object(* as parameter, where a string is required. 您正在传递一个不存在的对象(*作为参数,其中需要一个字符串。

(* actually, since filename exists (a string), it assumes you are trying to access its non-existing attribute (just like the error says). (*实际上,由于filename存在(一个字符串),因此它假定您正在尝试访问其不存在的属性 (就像错误所述)。

This should work: 这应该工作:

canvas = canvas.Canvas(filename, pagesize=letter)

This appends the .pdf suffix: 这将附加.pdf后缀:

canvas = canvas.Canvas(filename + '.pdf', pagesize=letter)

You should combine your variable filename with the extension .pdf 您应该将变量filename与扩展名.pdf结合使用

canvas = canvas.Canvas(filename+'.pdf', pagesize=letter)

if the variable doesn't contain the extension already 如果变量不包含扩展名

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

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