Last active
November 25, 2021 02:20
-
-
Save GabrielSGoncalves/57fc7dfbbadbf538e98c4ff298df8de0 to your computer and use it in GitHub Desktop.
Function for reading publicly open files from a Google Drive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Union, Dict | |
from io import StringIO | |
import json | |
import pandas as pd | |
import requests | |
def read_public_file_from_gdrive( | |
file_url: str, file_format: str, **kwargs | |
) -> Union[pd.DataFrame, Dict]: | |
"""Read public files stored in a Google Drive. | |
Parameters | |
---------- | |
file_url : str | |
Google Drive file URL. | |
file_format : str | |
Type of file format: 'csv', 'xlsx' or 'json'. | |
Returns | |
------- | |
Union[pd.DataFrame, Dict] | |
Dataframe (for 'csv' or 'xlsx') or Dictionary ('json') from Google | |
Drive file. | |
""" | |
download_url = ( | |
"https://drive.google.com/uc?export=download&id=" | |
+ file_url.split("/")[-2] | |
) | |
request_str_io = StringIO(requests.get(download_url).text) | |
if file_format == "csv": | |
return pd.read_csv(request_str_io, **kwargs) | |
elif file_format == "xlsx": | |
return pd.read_excel(download_url, **kwargs) | |
elif file_format == "json": | |
return json.load(request_str_io) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment