用列将表访问为CSV

时间:2018-06-28 06:49:01

标签: python python-2.7

我想将MS Access表转换为CSV。

MS Access表:

enter image description here

Python 2.7:

conn_string = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + file1 + ';'
conn = pyodbc.connect(conn_string)
cursor = conn.cursor()

cursor.execute('SELECT * FROM EMP')

with open(csvfile, 'wb') as f:
    writer = csv.writer(f)
    writer.writerows([i[0] for i in cursor.description])
    writer.writerows(cursor)

cursor.close()
conn.close()

但是得到意想不到的结果:

enter image description here

2 个答案:

答案 0 :(得分:1)

不要将列值写为行,这就是将其字符扩展为单个单元格的原因。要写标题,请使用:

writer.writerow([i[0] for i in cursor.description])

然后使用writer.writerows()写入实际数据。

答案 1 :(得分:1)

使用熊猫读取SQL并写入CSV

import pyodbc
import pandas as pd

打开连接

conn_string = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + file1 + ';'
conn = pyodbc.connect(conn_string)

将SQl查询结果读入Pandas数据框

query = "SELECT * FROM EMP"
dataf = pd.read_sql(query, conn)
conn .close()

保存为CSV

dataf.to_csv('./file_path')