Digital Farmer
Digital Farmer

Reputation: 2107

Python to import and save Google Sheets spreadsheet publicly saved in CSV format

The link is public and I'm wanting to save it within a project in vscode, I tried to do as below but I wasn't successful, how should I proceed to save this csv?

import csv
import urllib.request as urllib2

url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vSsbo0nGQZsYG0kEUC2dZnml_nIOp6q_KnhW8UmGQ39wafmWZQKg9Sb0u4ivBnXt3xrbJgBghpN6rNB/pub?gid=1242503396&single=true&output=csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)

with open("My_List.csv", "w+", newline="", encoding="UTF-8") as f:
    for row in cr:
        f.write(row)
        f.close()

Upvotes: 1

Views: 77

Answers (1)

Robson
Robson

Reputation: 2032

If you just want to download and save the file, you can do this:

import urllib.request as urllib2

url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vSsbo0nGQZsYG0kEUC2dZnml_nIOp6q_KnhW8UmGQ39wafmWZQKg9Sb0u4ivBnXt3xrbJgBghpN6rNB/pub?gid=1242503396&single=true&output=csv'
file = urllib2.urlopen(url).read()
with open("My_List.csv", "w+", newline="", encoding="UTF-8") as f:
    f.write(file.decode('UTF-8'))
    f.close()

Upvotes: 1

Related Questions