[Tutor] generating formatted output

Hugo Arts hugo.yoshi at gmail.com
Sun Sep 26 23:21:30 CEST 2010

On Sun, Sep 26, 2010 at 10:16 PM, Rance Hall <ranceh at gmail.com> wrote:
> My app will be printing a series of documents that are the same each
> time the doc is printed with the exception of the variables.  Sort of
> a MailMerge if you will.
> It seems to me that the easiest approach is to create a series of text
> files with the layout and placeholders I need (again much like
> MailMerge)
> And then do something like this:
>    file = open(fileName, "r") #Opens the file in read-mode
>    text = file.read() #Reads the file and assigns the value to a variable
>    file.close() #Closes the file (read session)
>    text = text.replace(sourceText, replaceText)  #there will be a
> series of these.
>    file = open(fileName2, "w") #Opens a new file in write-mode.
>    file.write(text)
>    file.close() #Closes the file (write session)
> Then you can print the file or email it or whatever you need to do.
> There wont be too many of these replacements (think invoice template
> with substitutes for customer information and a billing detail
> section.)
> So my question is about the approach.  Is this reasonable? Is there a
> better way to do this?

I would suggest you take a look at string.Template or the str.format
method. It may be somewhat simpler than doing a whole lot of replaces,
perhaps faster as well.



More information about the Tutor mailing list