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'
After the project is created you need to select it.
Enable the google Drive API for the project
Create the credentials by selecting the service account for the project.
Name the service account
Give editor access to it
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.
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.
Share this folder with the service account email address.
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}")
Output of the code
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.
Short Code explanation
You can see my project structure in image below.
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)
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()
After specifying the metadata to create the folder we execute the command
# 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.
#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.
# 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.
Top comments (1)
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.