analitics

Pages

Sunday, March 24, 2024

Python 3.12.1 : PrettyTable

A simple Python library for easily displaying tabular data in a visually appealing ASCII table format, see this webpage.
Let's install with pip tool:
pip install prettytable
Collecting prettytable
...
Successfully installed prettytable-3.10.0 wcwidth-0.2.13
Let's test with the default example:
from prettytable import PrettyTable
table = PrettyTable()
table.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
table.add_row(["Adelaide", 1295, 1158259, 600.5])
table.add_row(["Brisbane", 5905, 1857594, 1146.4])
table.add_row(["Darwin", 112, 120900, 1714.7])
table.add_row(["Hobart", 1357, 205556, 619.5])
table.add_row(["Sydney", 2058, 4336374, 1214.8])
table.add_row(["Melbourne", 1566, 3806092, 646.9])
table.add_row(["Perth", 5386, 1554769, 869.4])
print(table)
The result is this:
python test_001.py
+-----------+------+------------+-----------------+
| 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      |
+-----------+------+------------+-----------------+
Let's test with sqlite3 feature:
import sqlite3
from prettytable import from_db_cursor

try:
    # Connect to the database
    connection = sqlite3.connect("file_paths.db")
    cursor = connection.cursor()

    # Get the list of table names
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
    table_names = cursor.fetchall()
    # Print the table names
    for table in table_names:
        print(table[0])
        query = str('SELECT * FROM ' + table[0])
        cursor.execute(query)
        table_names = cursor.fetchall()
        print(table_names)
except sqlite3.Error as e:
    print(f"Error: {e}")

finally:
    # Close the connection
    connection.close()
The result for my sqlite3 file named file_paths.db and database named files is this:
files
[(1, 'C:/BACKUP/3D\\001.blend'), (2, 'C:/BACKUP/3D\\002.blend'), (3, 'C:/BACKUP/3D\\003.blend'), 
(4, 'C:/BACKUP/3D\\default_camera.blend')]
The result is according with the data from sqlite3 table.