irlmaks irlmaks - 1 year ago 81
Python Question

Python 3 - Saving a google spreadsheet as a csv

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

username = "username" //used the actual username, password and doc-id in the python scriptpassword = "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)

This is the error that IDLE is throwing up

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?

Answer Source

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)