我正在编写一个脚本,将 csv 文件读取到 psql 表,然后对数据进行排序并将其导出到一个新文件。如何将导出到 csv 文件的相同数据打印到终端以将其显示为表格?
这是我的代码:
import psycopg2
import pandas as pd
class 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)
犯罪嫌疑人X
相关分类