使用Python将数据保存到CSV-仅保存1行

时间:2019-01-28 17:31:21

标签: python sql csv

我有简单的Python脚本将数据保存到CSV文件

import csv
import MySQLdb

db = MySQLdb.connect('localhost', db="", user='', passwd='')

cursor = db.cursor()
sql = "SELECT col1, col2, col3, col4, col5 FROM table"

try:
    cursor.execute(sql)

    with open('MyFile.csv', mode='w') as csv_file:
        fieldnames = ['Col1_Name', 'Col2_Name', 'Col3_Name', 'Combined_Col']
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

        writer.writeheader()

        results = cursor.fetchall()
        for row in results:
           col1 = row[0]
           col2 = row[1]
           col3 = row[2]
           col4 = row[3]
           col5 = row[4]

           combinedColumns = "%s (count: %s)" % (col4, col5)

           writer.writerow({'Col1_Name': col1, 'Col2_Name' : col2, 'Col3_Name': col3, 'Combined_Col': combinedColumns})

except:
    print("Error: unable to fetch data")

db.close()

print("DONE!")

但是它只会保存一行。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

import csv
import MySQLdb

db = MySQLdb.connect('localhost', db="", user='', passwd='')

cursor = db.cursor()
sql = "SELECT col1, col2, col3, col4, col5 FROM table"

try:
    cursor.execute(sql)

    with open('MyFile.csv', mode='w', newlines='') as csv_file:
        fieldnames = ['Col1_Name', 'Col2_Name', 'Col3_Name', 'Combined_Col']
        writer = csv.writer(csv_file)

        writer.writerow(fieldnames)

        results = cursor.fetchall()
        for row in results:
           col1 = row[0]
           col2 = row[1]
           col3 = row[2]
           col4 = row[3]
           col5 = row[4]

           combinedColumns = "%s (count: %s)" % (col4, col5)

           writer.writerow(row)

except:
    print("Error: unable to fetch data")

db.close()

print("DONE!")