PythonLearner PythonLearner - 21 days ago 9
Python Question

Save MS Access tables as CSV

I am new to Python and request your kind assistance. I have five tables in the MS Access database and I need to compile a CSV file for each of the tables. One of the tables is Perm_Reviews, which is part of the snippet. Fortunately, I am able to query the MS Access data and it returns rows and the columns associated from the database. Can someone please provide assistance on how to store the tables as CSV files.

import pyodbc
import csv

conn_string = ("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=T:\\DataDump\\7.18.2016 PCR etrakit.accdb")

save_csv = 'C:\Desktop\CSVFiles'

conn = pyodbc.connect(conn_string)

cursor = conn.cursor()

SQL = 'select * from Perm_Reviews;'

for row in cursor.execute(SQL):
print row

cursor.close()
conn.close()

print 'All done for now'

Answer

I think this is what you are looking for.

import pyodbc
import csv

conn_string = ("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=T:\\DataDump\\7.18.2016 PCR etrakit.accdb") 

conn = pyodbc.connect(conn_string)

cursor = conn.cursor()

cursor.execute('select * from Perm_Reviews;')

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

cursor.close()
conn.close()