Table of Contents
Great Books of All Time
Home Backend Development Python Tutorial Generate file reports using Python's Template class

Generate file reports using Python's Template class

Apr 13, 2023 pm 06:13 PM
python template File report

Generate file reports using Python's Template class

Introduction

Many times, I find myself needing to perform tasks that generate reports, output files, or strings. They all more or less follow a pattern, and often the patterns are so similar that we want to have a template that we can reuse and feed data directly into. Fortunately, Python provides a class that can help us: string.Template.

In this article, you will learn how to use this class to generate an output file based on the data you are currently working with, and how to manipulate strings in the same way. So instead of just using examples that you might encounter in your day-to-day work, this article gives you a number of actual tools that you probably know that use this class for generating report files. Let’s get started!

Note: This article is based on Python 3.9.0 (CPython). You can find code examples used throughout this article on GitHub (https://github.com/DahlitzFlorian/generate-file-reports-using-pythons-template-class).

Before looking at an example, let's take some time to look at the advantages of using string.Template over other solutions.

1. No other dependencies are required and it works out of the box, so there is no need to use the pip install command to install it.

2. It is lightweight, and of course template engines such as Jinja2 and Mako have been widely used. However, in the scenario presented in this article, these capabilities are overstated.

3. Separation of concerns: Instead of embedding string manipulation and report generation directly in the code, you can use template files to move them to an external location. If you want to change the structure or design of your report, you can exchange template files without changing your code.

Due to these advantages, some well-known third-party libraries and tools are using it. Wily is an example, and in late 2018, Anthony Shaw, the inventor and maintainer of Wily, wanted to support HTML as the output format for reports generated by wily.

Example: Generating a report of the best books

After discussing the motivation behind using Python’s built-in string.Template class, we’ll look at the A practical example. Imagine that you work for a company that publishes an annual report on the best books published in the past year. 2020 is a special year because in addition to your annual report, you are also releasing a list of the best books of all time.

At this point, we don't care where the data comes from or which books are part of the list. For simplicity, let's assume we have a JSON file called data.json that contains a mapping of author names and book titles as shown below.

{
 "Dale Carnegie": "How To Win Friends And Influence People",
 "Daniel Kahneman": "Thinking, Fast and Slow",
 "Leo Tolstoy": "Anna Karenina",
 "William Shakespeare": "Hamlet",
 "Franz Kafka": "The Trial"
}
Copy after login

Your task now is to share it in a way that can be shared with others (for example, a large magazine, company or blogger). The company decided that a simple table in HTML format would suffice. Now the question is: how to generate this HTML table?

Of course, you can do this manually or create placeholders for each book. But it would be very desirable to have a more general version later, because the list content can be extended or the structural design changed.

Now we can take advantage of Python’s string.Template class! We start by creating the actual template as shown below. Here we call the file template.html.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Great Books of All Time</title>
 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
</head>
<body>
 
 <h1 id="Great-Books-of-All-Time">Great Books of All Time</h1>
 <table >
 <thead>
 <tr>
 <th scope="col">#</th>
 <th scope="col">Author</th>
 <th scope="col">Book Title</th>
 </tr>
 </thead>
 <tbody>
 ${elements}
 </tbody>
 </table>
 
</body>
</html>
Copy after login

The document itself is very rudimentary. We used bootstrap for styling and creating the basic structure of the final table. The header is included, but the data is still missing. Notice that within the tbody element, a placeholder ${elements} is used to mark where we will later inject the list of books.

We put all the Python scripts that are set up to produce the desired output! Therefore, we create a new Python file called report.py in the current working directory. First, we import the two built-in modules required and load the data from a JSON file.

# report.py
import json
import string
with open("data.json") as f:
 data = json.loads(f.read())
Copy after login

Now, the data variable is a dictionary containing the author’s name (key) and book title (value) as key-value pairs. Next, we generate the HTML table and put it into the template (remember placeholders?). So, we initialize an empty string, add new table rows to it as shown below.

content = ""
for i, (author, title) in enumerate(data.items()):
 content += "<tr>"
 content += f"<td>{i + 1}</td>"
 content += f"<td>{author}</td>"
 content += f"<td>{title}</td>"
 content += "</tr>"
Copy after login

This code snippet shows us looping through all the items in the data dictionary and placing the book title as well as the author's name in the corresponding HTML tags. We created the final HTML table. In the next step, we need to load the template file we created earlier:

with open("template.html") as t:
 template = string.Template(t.read())
Copy after login

Note that string.Template accepts a string, not a file path. Therefore, you can also provide a string previously created in the program without saving it to a file. In our case, we provide the contents of the template.html file.

Finally, we use the template's replace() method to replace the placeholder element with the string stored in the variable content. The method returns a string, which we store in the variable final_output. Last but not least, we create a new file called report.html and write the final output to that file.

final_output = template.substitute(elements=content)
with open("report.html", "w") as output:
 output.write(final_output)
Copy after login

现在已经生成了第一个文件报告!如果在浏览器中打开report.html文件,则可以看到结果。

safe_substitution()方法

现在,您已经构建了第一个string.Template用例,在结束本文之前,我想与您分享一个常见情况及其解决方案:安全替换。它是什么?

让我们举个例子:您有一个字符串,您想在其中输入一个人的名字和姓氏。您可以按照以下步骤进行操作:

# safe_substitution.py
import string
template_string = "Your name is ${firstname} ${lastname}"
t = string.Template(template_string)
result = t.substitute(firstname="Florian", lastname="Dahlitz")
print(result)
Copy after login

但是,如果您错过传递一个或另一个的值会怎样?它引发一个KeyError。为避免这种情况,我们可以利用safe_substitution()方法。在这种情况下,safe意味着Python在任何情况下都尝试返回有效字符串。因此,如果找不到任何值,则不会替换占位符。

让我们按以下方式调整代码:

# safe_substitution.py
import string
template_string = "Your name is ${firstname} ${lastname}"
t = string.Template(template_string)
result = t.safe_substitute(firstname="Florian")
print(result)# Your name is Florian ${lastname}
Copy after login

在某些情况下,这可能是一个更优雅的解决方案,甚至是必须的行为。但是这可能在其他地方引起意外的副作用。

本文概要

在阅读本文时,您不仅学习了Python字符串的基本知识。Template类以及使用它的原因,而且还实现了第一个文件报告脚本!此外,您已经了解了safe_substitution()方法以及在哪种情况下使用它可能会有所帮助。

The above is the detailed content of Generate file reports using Python's Template class. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles