I’m trying to write a Python script that can create a folder on Google Drive if it doesn’t exist already and then upload a file to it. Right now my code can only upload to existing folders and crashes if the folder isn’t there.
Here’s what I have so far:
import sys
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
target_dir = '2023_files'
upload_file = 'report_07_15_2023.xlsx'
g_auth = GoogleAuth()
g_auth.LocalWebserverAuth()
gdrive = GoogleDrive(g_auth)
root_files = gdrive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for item in root_files:
if item['title'] == target_dir:
folder_id = item['id']
new_file = gdrive.CreateFile({'title': upload_file, "parents": [{"kind": "drive#fileLink", "id": folder_id}]})
new_file.SetContentFile(upload_file)
new_file.Upload()
Can anyone help me modify this to create the target_dir folder if it’s not there? Thanks!
hey charlielion, i solved this using drive api v3. check for the folder with service.files().list() and create it with service.files().create() if missing. hope it works for you!
I’ve encountered this issue in my own projects. Here’s a more efficient approach you might consider:
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
creds = Credentials.from_authorized_user_file(‘token.json’, [‘https://www.googleapis.com/auth/drive.file’])
service = build(‘drive’, ‘v3’, credentials=creds)
def create_folder_if_not_exists(folder_name):
query = f"name=‘{folder_name}’ and mimeType=‘application/vnd.google-apps.folder’"
results = service.files().list(q=query, spaces=‘drive’).execute()
if not results[‘files’]:
folder_metadata = {‘name’: folder_name, ‘mimeType’: ‘application/vnd.google-apps.folder’}
folder = service.files().create(body=folder_metadata, fields=‘id’).execute()
return folder.get(‘id’)
return results[‘files’][0][‘id’]
folder_id = create_folder_if_not_exists(target_dir)
This method uses the Google Drive API v3, which is generally faster and more reliable than PyDrive. It checks for the folder’s existence and creates it if needed, all in one function call. You can then use this folder_id for your file upload.
I’ve dealt with a similar issue before, and I can share a solution that worked for me. You’ll want to modify your script to check if the folder exists first, and create it if it doesn’t. Here’s a snippet that should help:
folder_id = None
root_files = gdrive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for item in root_files:
if item['title'] == target_dir:
folder_id = item['id']
break
if not folder_id:
folder_metadata = {'title': target_dir, 'mimeType': 'application/vnd.google-apps.folder'}
folder = gdrive.CreateFile(folder_metadata)
folder.Upload()
folder_id = folder['id']
# Then continue with your file upload as before
This code first tries to find the folder. If it doesn’t exist, it creates a new one and retrieves its ID. After that, you can use this folder_id when uploading your file. Also, consider adding proper error handling to manage potential API errors.