How to convert, sort and save to CSV MS Access database .mdb file in Python
Question: I tried researching the answer but was not able to find a good solution. I
have files with strange extensions .res. I was told that they are MS Access
files. Not sure if they are the same as .mdb but I was able to open them in MS
Access. How can I open those files, extract necessary data, sort that data and
produce .csv file? I tried using this script:
<http://mazamascience.com/WorkingWithData/?p=168> and mdb tools on Linux. I
got some output with errors in terminal but all the files produced were blank.
It could be due to encoding. I am not sure. The file is in ASCII encoding I
think.

    
    
    Error: Table fo_Table
    Smart_Battery_Data_Table
    MCell_Aci_Data_Table
    Aux_Global_Data_Table
    Smart_Battery_Clock_Stretch_Table
     does not exist in this database.
    

On Windows I have no idea how to do it. My first step for now is just to dump
the necessary table from that database file into .csv. But ideally I need the
script to take the file, sort it, extract necessary data, do some calculations
(like data in one column divided by data in another column) and save all that
stuff into nice .csv. Thanks a lot. I am not an experienced programmer so
please have mercy.


Answer: Using the generic pyodbc library should do it. Looks like it has already an
embedded MS access driver. [This
question](http://stackoverflow.com/questions/1047580/ms-access-library-for-
python) can probably help you out.

I dont have any MS Access database files with me (It has been ages that I dont
have to work with them), but following [the
examples](https://code.google.com/p/pyodbc/wiki/GettingStarted) your code
should be something like this:

    
    
    import pyodbc
    
    db_file = r'''/path/to/the/file.res'''
    user = 'admin'
    password = 'password'
    odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=%s;UID=%s;PWD=%s' % (db_file, user, password)
    
    conn = pyodbc.connect(odbc_conn_str)
    
    cursor = conn.cursor()
    
    cursor.execute("select * from table order by some_column")
    
    for row in cursor.fetchall():
        print ", ".join((row.column1, row.column2, row.columnN))
    

