1. 程式人生 > >從csv中讀資料,並寫到csv中

從csv中讀資料,並寫到csv中

import pymysql
import numpy as np
import csv
def connectViogidata(ebayno):
    db = pymysql.connect(host='', user='s', passwd='2', db='viogidata', port=3306, charset='utf8')
    cursor = db.cursor()
    sql = ' select  id, ebayno, product_name, price, currency, when_time,shop_name from feedback where ebayno = %s'
    cursor.execute(sql,(ebayno))
    db.commit()
    cursor.close()
    db.close()
    result = cursor.fetchall()
    return result

if __name__ == '__main__':
    # 寫入到csv表中
    out = open("feedback_WM-D39S0106.csv","w",newline="")
    csv_writer = csv.writer(out)
    csv_writer.writerow(["id","ebayno","product_name","price","currency","when_time","shop_name"])

    #從csv檔案中讀取資料
    with open("1.csv",newline="") as f:
        reader = csv.reader(f)
        k = 0
        for row1 in reader:
            if k  == 0:  #去掉列名
                k = 1
                continue
            if len(row1) == 0:
                break
            ebayno = row1[0]
            feedback = connectViogidata(ebayno)  # 得到元組資料
            if feedback is not None:
                for row in feedback:  # 去掉外層括號
                    csv_writer.writerow([str(row[0]) , str(row[1]) , str(row[2]),str(row[3]) , str(row[4]), str(row[5]) , str(row[6]) ])