2

I have quite a small table, with 5 columns (inlcuding the primary key) and I am trying to export the data into a CSV file

import csv
with DbManager(#MY DATA BASE INFO) as db:
            SQLview = 'SELECT * FROM mytable;'
            db.cursor.execute(SQLview)
            writer = csv.writer(db)
            writer.writerow([ i[0] for i in cursor.description ]) 
            writer.writerows(cursor.fetchall())

However I am getting the error

writer = csv.writer(db)
TypeError: argument 1 must have a "write" method

TIA for any help or if you can point me in the right direction :)

2
  • 1
    What do you expect csv.writer(db) to do? You want to write to a file, not back to the database. Commented Aug 19, 2017 at 11:38
  • @AlexHall I used the documentation and thought that would create the file using the db data? Commented Aug 19, 2017 at 11:40

1 Answer 1

4

You need to open a file to output the data :

with DbManager(#MY DATA BASE INFO) as db:
    SQLview = 'SELECT * FROM mytable;'
    cursor = db.cursor()
    cursor.execute(SQLview)
    with open('output.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow([ i[0] for i in cursor.description ]) 
        writer.writerows(cursor.fetchall())
Sign up to request clarification or add additional context in comments.

1 Comment

I will accept your answer in two minutes when the timer allows me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.