Python and Google Drive: How to List and Create Files and Folders : 2023
Tags: python, googlecloud, drive, googledrive
Published: 2023-05-14 10:47:43

Google Drive is a popular cloud storage service that allows users to store, share, and access files from anywhere with an internet connection. With the help of the Google Drive API, developers can integrate Google Drive functionality into their applications, allowing users to perform a wide range of file operations programmatically. In this article, we'll explore how to use Python to interact with Google Drive, specifically focusing on listing files, creating files, and creating folders.

### Project setup:

On the [Google Cloud Dashboard](https://cloud.google.com/) dashboard start by creating new project, in the below image I created the project with name 'test-drive'

![Create new project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/npwqk315jhccf87rjaau.png)

After the project is created you need to select it.


![Select Project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x1yeo5efxzhkthawa6zq.png)

Enable the google Drive API for the project 


![Enable the Google Drive API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jkm128iuycq9jsdwii5y.png)

Create the credentials by selecting the service account for the project. 


![Select Service account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lk0prz31xka5e6ov1rwj.png)

Name the service account


![Name the service account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ib0kar05qfk9jqhqd7k.png)

Give editor access to it



![Give Editor access](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jfm4lpw33l79a2qdbb7c.png)



click Done to finish creation.

Select newly created service account and create new keys selecting Json option from prompt. Put the downloaded file in the project directory.


![Json Keys](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7t9au3dwjfp30s5k3s3w.png)

Rename the file "credentials.json". 

Create the New folder inside your google drive account where you want to create the file. I have created the folder with name "Test Drive". Note down the Id of the folder from the URL we need it in the script. 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2w67cppnvrzhvnjum4lc.png)


Share this folder with the service account email address.



![Share the folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dsha3kvmbdpm3u62gpxp.png)



Below given script create the folder inside the shred folder Name "Test Upload" , then it upload the file "image.webp" inside of that folder. And finally it list all the files inside of that folder. 

Link to code with requirements.txt https://gist.github.com/binary-ibex/eea137f2794fe3161959e77c2b34ea1e


```python
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google.oauth2 import service_account



# Replace 'FOLDER_NAME' with the name you want to give your new folder
folder_name = 'Test Upload'


# setup google drive
credentials = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=['https://www.googleapis.com/auth/drive']
    )
service = build("drive", "v3", credentials=credentials)
folder_metadata = {
    'name': folder_name,
    "parents": ['1Wsp5VthsToAWA3eF9wXCNcZPcL_JZFAi'],
    'mimeType': 'application/vnd.google-apps.folder'
}

# create folder 
new_folder = service.files().create(body=folder_metadata).execute()


#upload file inside the folder
file_metadata = {'name': 'image.webp', 'parents': [new_folder['id']]}
media = MediaFileUpload('image.webp')
file = service.files().create(body=file_metadata, media_body=media).execute()

# list the file inside of the folder
results = service.files().list(q=f"'{new_folder['id']}' in parents", fields="files(name)").execute()
items = results.get('files', [])
print(f"Files inside the folder , {items}")
```

Output of the code 

```bash
Files inside the folder , [{'name': 'image.webp'}]

```

As you can see we have the folder with name "Test Upload" and "image.webp" file inside of it. 


![Test Upload folder create on google drive](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p4824c43md348iydg0ir.png)

![Image file created inside of the folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ntti2q0glycjmmdarylk.png)


### Short Code explanation 

You can see my project structure in image below. 

![Project structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f9ln1nytdsa7elnqonos.png)

First we setup the google drive providing the path path of our credentials.json file 

```python
credentials = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=['https://www.googleapis.com/auth/drive']
    )
service = build("drive", "v3", credentials=credentials)

```

After that we create the folder, but to do that we need the Id of the shared folder, here we will use the Id of the shared folder we note before. Remember weather you are creating the file or folder, we need to specify the metadata for it 

```python 
folder_metadata = {
    'name': folder_name,
    "parents": ['1Wsp5VthsToAWA3eF9wXCNcZPcL_JZFAi'],
    'mimeType': 'application/vnd.google-apps.folder'
}

# create folder 
new_folder = service.files().create(body=folder_metadata).execute()
```
After specifying the metadata to create the folder we execute the command  

```python 
# create folder 
new_folder = service.files().create(body=folder_metadata).execute()
```

Now we will upload the local image file inside of newly created folder. We will use the MediaFileUpload class provided by the google client. For the parent we will use the ID of the newly created folder.

```python
#upload file inside the folder
file_metadata = {'name': 'image.webp', 'parents': [new_folder['id']]}
media = MediaFileUpload('image.webp')
file = service.files().create(body=file_metadata, media_body=media).execute()
```

We can list the file using the below code. Note in the below code 'fields' parameter is use to specify selective fields we want in response otherwise google will return lot of data. 

```python
# list the file inside of the folder
results = service.files().list(q=f"'{new_folder['id']}' in parents", fields="files(name)").execute()
items = results.get('files', [])
print(f"Files inside the folder , {items}")
```


That's it.