How to Import PrettyTable in Python

PrettyTable is an awesome Python library that allows us to generate simple ASCII tables. Not just ASCII tables, you can even use PrettyTable to generate HTML tables. Let’s understand how you can effortlessly import the PrettyTable module in Python.

Step 1: Installation of PrettyTable

Before importing PrettyTable in Python, you must first install it. You can simply use PyPi to install PrettyTable using pip using your terminal or command prompt. Use the following installation command.

Note: If you have other versions of Python and pip installed, you may need to use either pip3 or pip2.7 instead of pip.

Step 2: Import the PrettyTable Class

Once PrettyTable is installed, you can import it into your Python script. The method is straightforward. You only need to use the import keyword followed by the name of the module which is ‘prettytable’ in this case.

Step 3: Use PrettyTable

After importing the PrettyTable, you can use its numerous functions to generate tables. Below is a simple table creation example.

This script when executed properly will give you a tabular output with data formatted neatly. The ‘field_names’ method is used to define the column headers. ‘add_row’ is used to add data rows one by one to the table.

Entire Code:

Output

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |  1158259   |      600.5      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
|   Sydney  | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
|   Perth   | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

Conclusion

Successfully installing and importing PrettyTable in Python is as simple as following these steps. It’s a powerful tool that can help you format your data in both ASCII and HTML tables quickly and effortlessly.