DEV Community

Cover image for Python and Google Drive: How to List and Create Files and Folders : 2023
Chetan Dhongade
Chetan Dhongade

Posted on

Python and Google Drive: How to List and Create Files and Folders : 2023

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 dashboard start by creating new project, in the below image I created the project with name 'test-drive'

Create new project

After the project is created you need to select it.

Select Project

Enable the google Drive API for the project

Enable the Google Drive API

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

Select Service account

Name the service account

Name the service account

Give editor access to it

Give Editor access

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

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

Share this folder with the service account email address.

Share the folder

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

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}")
Enter fullscreen mode Exit fullscreen mode

Output of the code

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

Enter fullscreen mode Exit fullscreen mode

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

Image file created inside of the folder

Short Code explanation

You can see my project structure in image below.

Project structure

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

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

Enter fullscreen mode Exit fullscreen mode

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

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()
Enter fullscreen mode Exit fullscreen mode

After specifying the metadata to create the folder we execute the command

# create folder 
new_folder = service.files().create(body=folder_metadata).execute()
Enter fullscreen mode Exit fullscreen mode

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.

#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()
Enter fullscreen mode Exit fullscreen mode

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.

# 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}")
Enter fullscreen mode Exit fullscreen mode

That's it.

Top comments (1)

Collapse
 
ness profile image
nestor hernandez

muy bueno, pero sabes si puede bloquear los correos si se activa de esa manera, service account o nada que ver, te comento por que ayer realice el ejemplo y despues ya no podia recibir correos.

gracias.