In Python 3, open the file in text mode, and set newline
to ''
to let the CSV writer control what newlines are written:
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(worksheet.get_all_values())
Question
I am trying to save a private google spreadsheet into a csv. I have found another thread which has addressed this (Download a spreadsheet from Google Docs using Python), however the answers date back to 2012. There is a solution which I have tried to used, but I am running into errors. This is the code that I am currently using
import csv
import gspread
// used the actual username, password and doc-id in the python script
username = "username"
password = "password"
docid = "doc-id"
client = gspread.login(username, password)
spreadsheet = client.open_by_key(docid)
for i, worksheet in enumerate(spreadsheet.worksheets()):
filename = docid + '-worksheet' + str(i) + '.csv'
with open(filename, 'wb') as f:
writer = csv.writer(f)
writer.writerows(worksheet.get_all_values())
This is the error that IDLE is throwing up
writer.writerows(worksheet.get_all_values())
TypeError: 'str' does not support the buffer interface
As you must have realized, I am pretty much new to python and I am trying to solve this problem. Can anyone point out what the issue with the code that I am using?
Solution
In Python 3, open the file in text mode, and set newline
to ''
to let the CSV writer control what newlines are written:
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(worksheet.get_all_values())
OTHER TIPS
(Jul 2016) The use of GData is outdated when accessing Google Sheets files now. The current modern way to export a Google Sheet as CSV is by using the Google Drive API. I wrote a blogpost with a Python 2+3 code sample that shows you how to do this. Also check the other thread where I added an answer more modern than 2012. With that update, this thread should be marked as a duplicate of that other one. To access Google Sheets from Python in a more general sense, check this answer I gave to a related question.