How do I create a CSV file from database in Python?

前端 未结 8 2020
南方客
南方客 2020-12-05 00:05

I have a Sqlite 3 and/or MySQL table named \"clients\"..

Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect...

8条回答
  •  春和景丽
    2020-12-05 01:02

    This is simple and works fine for me.

    Lets say you have already connected to your database table and also got a cursor object. So following on on from that point.

    import csv
    curs = conn.cursor()
    curs.execute("select * from oders")
    m_dict = list(curs.fetchall())
    
    with open("mycsvfile.csv", "wb") as f:
        w = csv.DictWriter(f, m_dict[0].keys())
        w.writerow(dict((fn,fn) for fn in m_dict[0].keys()))
        w.writerows(m_dict)
    

提交回复
热议问题