dump csv from sqlalchemy

前端 未结 8 489
时光取名叫无心
时光取名叫无心 2020-12-02 17:48

For some reason, I want to dump a table from a database (sqlite3) in the form of a csv file. I\'m using a python script with elixir (based on sqlalchemy) to modify the datab

8条回答
  •  难免孤独
    2020-12-02 18:10

    I spent a lot of time searching for a solution to this problem and finally created something like this:

    from sqlalchemy import inspect
    
    with open(file_to_write, 'w') as file:
        out_csv = csv.writer(file, lineterminator='\n')
    
        columns = [column.name for column in inspect(Movies).columns][1:]
        out_csv.writerow(columns)
    
        session_3 = session_maker()
    
        extract_query = [getattr(Movies, col) for col in columns]
        for mov in session_3.query(*extract_query):
            out_csv.writerow(mov)
    
        session_3.close()
    

    It creates a CSV file with column names and a dump of the entire "movies" table without "id" primary column.

提交回复
热议问题