I’m working on a Python script that uploads files to Google Drive. My current code works fine when the target directory already exists, but it crashes when the directory is missing.
Here’s what I have so far:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
directory_name = '2023_reports'
upload_filename = 'monthly_summary_data.xlsx'
auth = GoogleAuth()
auth.LocalWebserverAuth()
gdrive = GoogleDrive(auth)
files = gdrive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for item in files:
if item['title'] == directory_name:
folder_id = item['id']
break
new_file = gdrive.CreateFile({
'title': upload_filename,
"parents": [{"kind": "drive#fileLink", "id": folder_id}]
})
new_file.SetContentFile(upload_filename)
new_file.Upload()
The problem is that when the folder doesn’t exist, the variable folder_id is never set and my script fails. How can I modify this code to automatically create the folder if it’s not found before uploading the file?
I fixed this by completely refactoring the search logic. Ditched the for loop with break statements and made a helper function that either returns the existing folder ID or creates a new one. Something like folder_id = get_or_create_folder(gdrive, directory_name, 'root') - the function handles the ListFile query, searches results, and if there’s no match it calls CreateFile with the folder mimetype. Way cleaner since you always get a valid folder_id back whether the folder existed or not. I use this pattern in all my automation scripts now. Kills the undefined variable problem and keeps the code readable.
make sure to check if folder_id is None after your loop. if it is, create the folder first using CreateFile with the mimeType for folders. then you can upload your file to that new folder’s ID. hope that helps!
Wrap your folder search in a try-except block or use a flag variable to check if it exists. I ran into this exact problem when automating report uploads for my team. After the loop, check if folder_id exists - if not, create it with gdrive.CreateFile and set mimeType to ‘application/vnd.google-apps.folder’. Set folder_found = False before the loop, flip it to True when you find the folder, then create the directory if it’s still False. Been using this in production for months with zero failures.