使用请求(或其他库)以 CSV 格式访问公共 Google 表格的内容 [英] Accessing the contents of a public Google Sheet as CSV using Requests (or other library)

查看:23
本文介绍了使用请求(或其他库)以 CSV 格式访问公共 Google 表格的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个小型 Python 程序,可以处理来自 CSV 文件的数据.我正在跟踪谷歌工作表中的一些数字,并通过下载谷歌工作表创建了 CSV 文件.我试图找到一种方法让 python 直接从谷歌表格读取 CSV 文件,这样我在更新电子表格时就不必下载新的 CSV.

I wrote a small python program that works with data from a CSV file. I am tracking some numbers in a google sheet and I created the CSV file by downloading the google sheet. I am trying to find a way to have python read in the CSV file directly from google sheets, so that I do not have to download a new CSV when I update the spreadsheet.

我看到 requests 库可能能够处理这个问题,但我很难弄清楚.我选择不尝试 google API,因为只要我不介意将工作表公开给那些有链接的人,这种方式似乎更简单,这很好.

I see that the requests library may be able to handle this, but I'm having a hard time figuring it out. I've chosen not to try the google APIs because this way seems simpler as long as I don't mind making the sheet public to those with the link, which is fine.

我尝试使用请求文档,但我是一名新手程序员,无法将其作为 CSV 读取.

I've tried working with the requests documentation but I'm a novice programmer and I can't get it to read in as a CSV.

这是当前将数据带入python的方式:

This is how the data is currently taken into python:

file = open('data1.csv', newline='')
reader = csv.reader(file)

我希望 file = open() 理想情况下被请求库替换并直接从电子表格中提取.

I would like the file = open() to ideally be replaced by the requests library and pull directly from the spreadsheet.

推荐答案

您需要找到下载文件的正确 URL 请求.

You need to find the correct URL request that download the file.

示例网址:

csv_url='https://docs.google.com/spreadsheets/d/169AMdEzYzH7NDY20RCcyf-JpxPSUaO0nC5JRUb8wwvc/export?format=csv&id=169AMdEzYzH7NDY20RCcyf-JpxPSUaO0nC5JRUb8wwvc&gid=0'

这样做的方法是手动下载您的文件,同时在浏览器的开发者工具的网络选项卡中检查请求 URL.

The way to doing it is by manually download your file while inspecting the requests URL at the Network tab in the Developer Tools in your browser.

那么以下就足够了:

import requests as rs
csv_url=YOUR_CSV_DOWNLOAD_URL
res=rs.get(url=csv_url)
open('google.csv', 'wb').write(res.content)

它会将名为 'google.csv' 的 CSV 文件保存在您的 Python 脚本文件的文件夹中.

It will save CSV file with the name 'google.csv' in the folder of you python script file.

这篇关于使用请求(或其他库)以 CSV 格式访问公共 Google 表格的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆