简体   繁体   中英

saving a variable filename in reportlab

I keep getting an error " no attribute for string .pdf" with my code. 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.

    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).

This should work:

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

This appends the .pdf suffix:

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

You should combine your variable filename with the extension .pdf

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

if the variable doesn't contain the extension already

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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