我正在編寫一個(gè)腳本,將 csv 文件讀取到 psql 表,然后對(duì)數(shù)據(jù)進(jìn)行排序并將其導(dǎo)出到一個(gè)新文件。如何將導(dǎo)出到 csv 文件的相同數(shù)據(jù)打印到終端以將其顯示為表格?這是我的代碼:import psycopg2import pandas as pdclass Products(object): def __init__(self): self.db_connection = psycopg2.connect("host=localhost dbname=rd_assignment user=postgres") self.db_cur = self.db_connection.cursor() def add_column(self): """This method adds a column to the products database table. It checks if the table is empty before inserting the csv file.""" self.db_cur.execute("ALTER TABLE products ADD COLUMN IF NOT EXISTS is_active BOOLEAN NOT NULL;") self.db_cur.execute("SELECT COUNT(*) FROM products;") rows = self.db_cur.fetchall() if rows[0][0] < 20: self.db_cur.execute( "COPY products FROM '/Users/leroy/PycharmProjects/rd_assignment/products.csv' DELIMITERS ',' CSV;") self.db_connection.commit() def sort_highest(self): """This method outputs the products to a csv file according to the highest amount""" sort_highest = "COPY (SELECT * FROM products order by amount desc) TO STDOUT DELIMITER ';' CSV HEADER" with open("highest_amount.csv", "w") as file: self.db_cur.copy_expert(sort_highest, file) r = pd.read_csv('/Users/leroy/PycharmProjects/rd_assignment/highest_amount.csv') print(r.head(20)) def get_active(self): """This method outputs the active products in the database to a csv file""" sort_active = "COPY (SELECT * FROM products WHERE is_active = True) TO STDOUT DELIMITER ';' CSV HEADER" with open("active_products.csv", "w") as file: self.db_cur.copy_expert(sort_active, file)
3 回答

犯罪嫌疑人X
TA貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個(gè)贊
嘗試漂亮。
from prettytable import PrettyTable
x = PrettyTable()
x.field_names = ["Sl.n0", "date1", "date2", "comments","Boolean"]
with open('file.csv') as f:
line = f.readline()
while line:
x.add_row(line.rstrip().split(','))
line = f.readline()
print x
使用 pip 安裝: pip install PrettyTable
添加回答
舉報(bào)
0/150
提交
取消