第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何使用python將csv數(shù)據(jù)輸出到終端

如何使用python將csv數(shù)據(jù)輸出到終端

森林海 2021-06-21 09:43:55
我正在編寫一個(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


查看完整回答
反對(duì) 回復(fù) 2021-06-29
  • 3 回答
  • 0 關(guān)注
  • 268 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)