Skip to content Skip to sidebar Skip to footer

How To Upload Csv File Into Google Drive And Read It From Same Into Python

I have a google drive which I have my csv file uploaded in already, the link to share that file is given as: https://drive.google.com/open?id=1P_UYUsgvGXUhPCKQiZWlEAynKoeldWEi I a

Solution 1:

You don't need that much out of that example to upload a file to google drive:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

# access the drive
gauth = GoogleAuth()
drive = GoogleDrive(gauth)

# the file you want to upload, here simple example
f = drive.CreateFile()
f.SetContentFile('document.txt')

# upload the file
f.Upload()
print('title: %s, mimeType: %s' % (f['title'], f['mimeType']))

# read all files, the newly uploaded file will be there
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
  print('title: %s, id: %s' % (file1['title'], file1['id']))

Note: I created an empty file in this example instead of an existing one, you just have to change it to load up the csv file from your local pc where the python file is running on instead.

Kind regards

Solution 2:

Here is a simple approach I use for all my csv files stored in Google Drive.

First import the necessary libraries that will facilitate your connection.

  !pip install -U -q PyDrivefrom google.colabimport auth
    from pydrive.authimportGoogleAuthfrom pydrive.driveimportGoogleDrivefrom oauth2client.clientimportGoogleCredentials

Next step is authentication and creating the PyDrive client in order to connect to your Drive.

This should give you a link to connect to Google Cloud SDK.

Select the Google Drive account you want to access. Copy the link and paste it onto the text field prompt on your Colab Notebook.

auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

To get the file, you will need the id of the file in Google Drive.

downloaded = drive.CreateFile({'id':'1P_UYUsgvGXUhPCKQiZWlEAynKoeldWEi'}) # replace the id with id of the file you want to access
downloaded.GetContentFile('file.csv')  

Finally, you can read the file as pandas dataframe.

import pandas as pd
df= pd.read_csv('fle.csv') 

Post a Comment for "How To Upload Csv File Into Google Drive And Read It From Same Into Python"