为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用python将csv数据输出到终端

如何使用python将csv数据输出到终端

森林海 2021-06-21 09:43:55
我正在编写一个脚本,将 csv 文件读取到 psql 表,然后对数据进行排序并将其导出到一个新文件。如何将导出到 csv 文件的相同数据打印到终端以将其显示为表格?这是我的代码: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贡献2080条经验 获得超4个赞

尝试漂亮。


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


查看完整回答
反对 回复 2021-06-29
  • 3 回答
  • 0 关注
  • 253 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号