I need to add a new file in a nested folder on Google Drive using Google Drive api in the form YYYY/MM/DD/HH/mm/file where the dates are dynamically created basing on the current date.
For example:
2021/06/16/11/30/my_file.csv
I created the following script in Python, but it is creating one single folder (named "2021/06/16/11/30") instead of the desired nested structure (multiple nested folders named "06", "11" and "30") inside the parent folder "2021":
from googleapiclient.discovery import build
import google.auth
from googleapiclient.http import MediaFileUpload
SCOPES = ['https://www.googleapis.com/auth/drive.metadata', 'https://www.googleapis.com/auth/drive']
credentials, project_id = google.auth.default(scopes=SCOPES)
service = build('drive', 'v3', credentials=credentials)
folder_id = 'parent-folder-id'
# Create folder
file_metadata = {
'name': '2021/06/16/11/30',
'mimeType': 'application/vnd.google-apps.folder',
'parents': [folder_id],
}
file = service.files().create(body=file_metadata, fields='id').execute()
new_folder_id = file.get('id')
print(f'Folder ID: {new_folder_id}')
# Upload file
file_metadata = {
'name': 'my_file.csv',
'parents': [new_folder_id],
}
media = MediaFileUpload('my_file.csv', mimetype='text/csv', resumable=True)
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
print(f'Folder ID: {file.get("id")}')
Is there a way to create such nested folder structure in one call instead of iterate on each folder creation and pass the new folder id as new parent id?
2021, next folder06in2021, etc.? Google drive doesn't have to use the same rules as local system. it may treat/as normal char, not separator.os.makdirs()raise error when folder exist and you have to check ifos.path.exists(). In web drivers is even worst because they may have two folders with the same name because they uses ID to recognize folders.