6

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user2869276
  • 149
  • 1
  • 3
  • 10

4 Answers4

12

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.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • I just tried that: data = x.get_string() numpy.savetxt(('data.txt'),data) and got an Indexerror: Tuple index out of range. – user2869276 Mar 16 '14 at 01:11
  • 1
    @user2869276 I've included an example that writes the data to a text file, please check. – alecxe Mar 16 '14 at 01:16
  • This works! I tried to save my prettytable.get_string() in a .csv file. The only thing to add is------ with open('file.csv', 'wb', encoding='utf-8') as f: Hope someone finds this helpful :) – hansrajswapnil Aug 08 '21 at 05:20
1

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

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

LUân Đào Duy
  • 81
  • 1
  • 2
  • 10
1

using open and write method to save data to test.txt file.

Try the following code,

with open('test.txt', 'w') as f:
    f.write(data)
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81
1
with open('test.txt', 'w') as f:
    f.write(data)

The above snippet will throw an error as the data will be of type prettytable. You need to typecast the data object to a str first, like this:

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

The file will now be saved locally.

Andreas Violaris
  • 2,465
  • 5
  • 13
  • 26