亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用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 關注
  • 271 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號