因此,我正在使用“prettytable”库,并能够在执行时获取打印的数据表。但是,我不知道如何将其保存到文件中。理想情况下,我希望将该表保存为pdf,以便将其用于报告。

以下是prettytable网页本身的示例代码:

from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
x.align["City name"] = "l" # Left align city names
x.padding_width = 1 # One space between column edges and contents (default)
x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
print x

最佳答案

使用get_string()方法,文档字符串引用:

def get_string(self, **kwargs):

    """Return string representation of table in current state.
       ...
    """

例:
from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])

...

data = x.get_string()

with open('test.txt', 'wb') as f:
    f.write(data)

这将创建一个test.txt文件,其中包含您的prettytable。

希望能有所帮助。

08-24 23:43