【发布时间】:2023-01-18 21:02:19
【问题描述】:
如何在不下载文件的情况下将 Google 电子表格的内容读入 Pandas 数据框?
我认为 gspread 或 df2gspread 可能是不错的选择,但到目前为止我一直在使用 pydrive 并接近解决方案。
使用 Pydrive,我设法获得了我的电子表格的导出链接,作为 .csv 或 .xlsx 文件。在身份验证过程之后,这看起来像
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
# choose whether to export csv or xlsx
data_type = 'csv'
# get list of files in folder as dictionaries
file_list = drive.ListFile({'q': "'my-folder-ID' in parents and
trashed=false"}).GetList()
export_key = 'exportLinks'
excel_key = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
csv_key = 'text/csv'
if data_type == 'excel':
urls = [ file[export_key][excel_key] for file in file_list ]
elif data_type == 'csv':
urls = [ file[export_key][csv_key] for file in file_list ]
我为 xlsx 获得的 url 类型是
https://docs.google.com/spreadsheets/export?id=my-id&exportFormat=xlsx
和csv类似
https://docs.google.com/spreadsheets/export?id=my-id&exportFormat=csv
现在,如果我点击这些链接(或使用webbrowser.open(url)访问它们),我下载文件,然后我通常可以使用 pandas.read_excel() 或 pandas.read_csv() 将其读入 Pandas 数据帧,如 here 所述。
如何跳过下载,直接从这些链接将文件读入数据框?
我尝试了几种解决方案:
-
The obvious
pd.read_csv(url)给
pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 6, saw 2
有趣的是,这些数字 (1, 6, 2) 不依赖于我的电子表格中的行数和列数,这表明该脚本试图读取的内容并非其预期内容。
- 类似物
pd.read_excel(url)给出
ValueError: Excel file format cannot be determined, you must specify an engine manually.
并指定例如engine = 'openpyxl'给出
zipfile.BadZipFile: File is not a zip file
- BytesIO 解决方案看起来很有希望,但是
r = requests.get(url)
data = r.content
df = pd.read_csv(BytesIO(data))
仍然给
pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 6, saw 2
如果我print(data)我得到数百行html代码
b'\n<!DOCTYPE html>\n<html lang="de">\n <head>\n <meta charset="utf-8">\n <meta content="width=300, initial-scale=1" name="viewport">\n
...
...
</script>\n </body>\n</html>\n'
【问题讨论】:
标签: python pandas google-drive-api pydrive