Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save table from prettytable?

So I am using the library 'prettytable' and am able to get a table of my data printed upon execution. However, I have no idea how to save it to a file. Ideally I'd like the table to be saved in a pdf so I could use it for my report.

Here is an example code from the prettytable webpage itself:

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

table

like image 524
user2869276 Avatar asked Jan 12 '23 00:01

user2869276


2 Answers

Use get_string() method, docstring quote:

def get_string(self, **kwargs):

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

Example:

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)

This will create a test.txt file with your prettytable inside.

Hope that helps.

like image 92
alecxe Avatar answered Jan 22 '23 01:01

alecxe


@Komal Jaswani You should change 'wb' mode to 'w' mode.

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

like image 31
LUân Đào Duy Avatar answered Jan 22 '23 00:01

LUân Đào Duy