Soumya
Soumya

Reputation: 5412

database to csv in django using python

I am writing this small code which is part of my Django application. It is supposed to pick up data from a DB table(MySql) and make a csv file. May be its a very simple error I am getting, but I am not able to resolve it.

Name of the file: write_to_csv.py

import csv  
def createCSV():  
    from django.db import connection, transaction  
    cursor = connection.cursor()  
    cursor.execute("select * from avg_max_min;")  
    csv_writer = csv.writer(open("out.csv", "wt"), delimiter=',')  
    csv_writer.writerow([i[0] for i in cursor.description]) # write headers  
    csv_writer.writerows(cursor)  
    del csv_writer # this will close the CSV file  

Error
Exception Value:
'module' object has no attribute 'writer'
Exception Location: C:\Python26\Lib\site-packages\django\bin\report\src\report ..\report\report_view\write_to_csv.py in createCSV, line 6

Upvotes: 0

Views: 1887

Answers (2)

mgalgs
mgalgs

Reputation: 16779

I'm guessing it's a setup problem (something like this). Make sure you don't have a file named csv.py or some other weirdness that is "hiding" python's csv module.

Upvotes: 1

Sean Vieira
Sean Vieira

Reputation: 159905

open's second argument should be wb not wt. Other than that, it looks like you are doing everything right.

If it's still not working, can you update your question with the results of doing dir(csv)? (It's most likely that you have some other module installed in your Python distribution or in the same directory as write_to_csv.py with the same name.)

Upvotes: 2

Related Questions