简介
tabulate 是一个用于在 Python 中生成美观的格式化表格的第三方库。它可以将数据(如列表、字典、Pandas DataFrame 等)转换为多种表格格式(如纯文本、HTML、Markdown 等),适用于命令行工具、日志输出、报告生成等场景。
基础用法
基本表格生成
from tabulate import tabulate
data = [
["Alice", 28, "Engineer"],
["Bob", 32, "Data Scientist"],
["Charlie", 25, "Designer"]
]
headers = ["Name", "Age", "Job"]
# 生成纯文本表格
print(tabulate(data, headers=headers, tablefmt="grid"))
输出:
+---------+-----+-----------------+
| Name | Age | Job |
+=========+=====+=================+
| Alice | 28 | Engineer |
+---------+-----+-----------------+
| Bob | 32 | Data Scientist |
+---------+-----+-----------------+
| Charlie | 25 | Designer |
+---------+-----+-----------------+
对齐控制
通过 colalign 参数指定每列对齐方式:
print(tabulate(
data,
headers=headers,
tablefmt="presto",
colalign=("left", "center", "right")
))
输出
Name | Age | Job
--------+-----+-----------------
Alice | 28 | Engineer
Bob | 32 | Data Scientist
Charlie| 25 | Designer
从字典生成表格
data_dict = [
{"Name": "Alice", "Age": 28, "Job": "Engineer"},
{"Name": "Bob", "Age": 32, "Job": "Data Scientist"}
]
print(tabulate(data_dict, headers="keys", tablefmt="fancy_grid"))
输出
╒═════════╤══════╤══════════════════╕
│ Name │ Age │ Job │
╞═════════╪══════╪══════════════════╡
│ Alice │ 28 │ Engineer │
├─────────┼──────┼──────────────────┤
│ Bob │ 32 │ Data Scientist │
╘═════════╧══════╧══════════════════╛
输出到文件
生成 HTML 报告:
html_table = tabulate(data, headers=headers, tablefmt="html")
with open("report.html", "w") as f:
f.write(html_table)