I have a program when it currently reads from a database, which can be found here. I have users choose a specific record they want to display so the SQL command will execute that record. Now I have a table that currently displays those records, however, the columns are not how I wanted to look because I am dealing with long strings of data.
I am not using any extended libraries. My table display is sort of equal for some tables except tables like Suppliers, Orders, Categories. The width for each column is way too long. It takes too much space.
I think my code currently takes the longest string from the whole table and set the width of that for each column. What I want it to do instead is to take the longest string for each column and NOT the whole table, so the width of each column is set by string length (with like a little extra space of course) of that column.
Here is my code so far:
import sqlite3
def read_display(record):
database = 'data.db'
connection = sqlite3.connect(database)
c = connection.cursor()
# selects a table to display
sql = "SELECT * FROM {0}".format(record)
cursor.execute(sql)
conn.commit()
results = cursor.fetchall()
header = [i[0] for i in c.description]
data = [header] + list(tuple(results))
width = max((len(str(x)) for d in data for x in d))
for i, d in enumerate(data):
line = ' | '.join(str(x).ljust(width) for x in d)
print(line)
if i == 0:
print('-' * len(line))
I tried to mess with the width
variable, but I can't seem to figure it out. I tried looking at other StackOverflow q's but they are dealing with little data, so it is easier to set the width. This data contains huge strings.
Thank you so much!