【问题标题】:Save data to CSV with Python - will save only 1 row使用 Python 将数据保存到 CSV - 仅保存 1 行
【发布时间】:2019-01-28 17:31:20
【问题描述】:

我有简单的 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!")

但它只会保存一行。

我错过了什么?

【问题讨论】:

  • 请分享错误日志
  • 尝试导入系统
  • @ShrikantShete 我已经更新了 OP。已保存数据,但只有 1 行
  • 不要使用通用的 try/except;它隐藏了您的错误,使调试代码变得更加困难。去掉 try/except 就会看到真正的错误
  • @JackTheKnife 我的观点仍然成立,如果你有一个通用的尝试/除非你得到一个通用的“无法获取数据”而不是真正的错误。永远不要做一个通用的 try/except。

标签: python sql csv


【解决方案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!")

【讨论】:

  • 现在该行会失败。
  • 我的错,我错过了参数
  • 根据csv module documentation,您必须使用newlines='' 打开文件才能正确添加新行:with open('MyFile.csv', mode='w', newlines='') as csv_file:
猜你喜欢
  • 1970-01-01
  • 2016-01-05
  • 2017-11-01
  • 2018-09-11
  • 1970-01-01
  • 2016-11-04
  • 2016-12-21
  • 2017-08-14
  • 1970-01-01
相关资源
最近更新 更多