Skip to content

Instantly share code, notes, and snippets.

@binary-ibex
Created May 14, 2023 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binary-ibex/eea137f2794fe3161959e77c2b34ea1e to your computer and use it in GitHub Desktop.
Save binary-ibex/eea137f2794fe3161959e77c2b34ea1e to your computer and use it in GitHub Desktop.
Python script to Create Folder, Upload File and List Files inside folder in google Drive using Google Drive API
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}")
cachetools==5.3.0
certifi==2022.12.7
charset-normalizer==3.1.0
google-api-core==2.11.0
google-api-python-client==2.86.0
google-auth==2.17.3
google-auth-httplib2==0.1.0
googleapis-common-protos==1.59.0
httplib2==0.22.0
idna==3.4
protobuf==4.22.4
pyasn1==0.5.0
pyasn1-modules==0.3.0
pyparsing==3.0.9
python-dotenv==1.0.0
requests==2.30.0
rsa==4.9
six==1.16.0
uritemplate==4.1.1
urllib3==2.0.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment