How to import a csv file hosted in your google drive

There are numerous ways to make your code reusable & minimize dependencies.

One of the common challenges we face is every time we do an analysis we need to import a data file from local machine. One way to get rid of this dependency is to host the file in google drive and use the url to import.

This can be achieved as follows.

In this example we use a csv file.

We uploaded a file named "healthcare-dataset-stroke-data.csv" to google drive. It looks something like this.



Now go to options on this file uploaded in google drive and change the access to "Anyone with the link" as shown here.


When this is done, open the same csv file in a new window.



This step is important.

Now we take out the unique ID google generates for our file. You can find the unique ID in the highlighted portion of the url.


This unique id is different from the one you see in the previous window. If you don't hit the "open in new window" option & take the ID from the previous window as shown below. It won't work as the two urls are very different.


Please note if you take this ID, this won't work!!

Now as we have copied the ID from the url by opening the csv in a new window, we put this into the below code:



df = pd.read_csv("https://drive.google.com/uc?export=download&id=1AaUsEwFoAbHy1m1AFECwYsZmcdcIDPg3")
df.head(2)

Mark that the url is not the same. You just need to change the unique Code and the pandas read_csv method should work.

Thanks for reading. Happy Coding :)







0 Comments