2

I've managed to convert a .mdb file to .csv, based on this post: How to export MS Access table into a csv file in Python using e.g. pypyodbc.

However, I can not get the metadata (column name) from the original file. Does anyone have a clue on how to do that?

Thanks!

Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
Coraline
  • 23
  • 4
  • Have you had a look at this https://stackoverflow.com/questions/15098747/getting-table-and-column-names-in-pyodbc ? – David Mar 20 '20 at 00:13

1 Answers1

3

Simply retrieve headers from cursor.description where you will call writerow just before iterating through cursor results:

# OPEN CSV AND ITERATE THROUGH RESULTS
with open('CSVDatabaseWithHeaders.csv', 'w', newline='') as f:
    writer = csv.writer(f)    
    # ADD LINE BEFORE LOOP
    writer.writerow([i[0] for i in cur.description])  

    for row in cur.fetchall() :
        writer.writerow(row)
Parfait
  • 104,375
  • 17
  • 94
  • 125