The code below will iterate over a list of tuples that SELECT (execute) returns.
for row in cursor.execute("SELECT * FROM table"):
write_file.write(row)
Eg.
If you have a database with rows number, word, colour your code will loop over something like this:
(23, "tree", "red")
(17, "code", "green")
(11, "python", "yellow")
And what you're trying to do is write a tuple to a file. You can only write strings (or bytes) to a file.
What you have to do is convert that tuple to a string. For this you can use the join() function.
Your code will now look like this:
c.execute("SELECT * FROM table")
table = c.fetchall()
print(table)
#to export as csv file
with open("wub.csv", "wb") as write_file:
cursor = connection.cursor()
for row in cursor.execute("SELECT * FROM table"):
writeRow = " ".join(row)
write_file.write(writeRow)
" ".join(row) will join all tuple elements and seperate them with, in this case, a space.
There are a few problems with this.
Join only works with lists and tuples that contain string elements only (so the code above wouldn't work if your database had a REAL or INTEGER type)
You can just write a loop that goes over each element in the list and converts it to a string.
I also added a .encode() because you are opening your CSV file with "rb" so you need to convert it to bytes before writing to the file.
c.execute("SELECT * FROM table")
table = c.fetchall()
print(table)
#to export as csv file
with open("wub.csv", "wb") as write_file:
cursor = connection.cursor()
for row in cursor.execute("SELECT * FROM table"):
writeRow = " ".join([str(i) for i in row])
write_file.write(writeRow.encode())
write_file.write(",".join(row))fix it? Maybewrite_file.write(",".join(row) + "\n")in case it doesn't add a newline automatically. Anyway, as @cricket_007's link suggests, there's also a module for handling csv files