Coraline
Coraline

Reputation: 23

Including column names when converting an .mdb file to .csv in Python

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!

Upvotes: 2

Views: 2315

Answers (1)

Parfait
Parfait

Reputation: 107767

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)

Upvotes: 3

Related Questions