Python prettytable – Tabulate a CSV file

In this post we will be creating a Python script that will tabulate data within a CSV file. To do this we will be using the ‘prettytable‘ library, used for displaying tabular data in a visually appealing format.

To install the prettytable library run the following command.

pip install prettytable

See below an image of our CSV file for this example containing three columns ‘Rank’, ‘Name’ and ‘Platform’.

CSV file to be printed in tabular format

To tabulate the above CSV file we would use the snippet of Python code below.

from prettytable import from_csv

with open("Sample.csv") as f:
    table = from_csv(f)
    
print(table)

The above would return the following as output.

+------+---------------------------+----------+
| Rank |            Name           | Platform |
+------+---------------------------+----------+
|  1   |         Wii Sports        |   Wii    |
|  2   |     Super Mario Bros.     |   NES    |
|  3   |       Mario Kart Wii      |   Wii    |
|  4   |     Wii Sports Resort     |   Wii    |
|  5   |  Pokemon Red/Pokemon Blue |    GB    |
|  6   |           Tetris          |    GB    |
|  7   |   New Super Mario Bros.   |    DS    |
|  8   |          Wii Play         |   Wii    |
|  9   | New Super Mario Bros. Wii |   Wii    |
|  10  |         Duck Hunt         |   NES    |
+------+---------------------------+----------+
>>> 

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply