'Create nested folders with Google Drive API

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?



Solution 1:[1]

The files.create API creates only one file, and cannot create multiple files on a single call. So to answer your question, you need to create 2021 first, set the newly created folder ID as the parent, then iterate folder creation (06, 16, so on) until you reach the bottom level.

Sample:

folder_id = 'parent-folder-id'

date_array = ["2021", "06", "16", "11", "30"]

for x in date_array:
  # Create folder
  file_metadata = {
      'name': x,
      '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}')
  folder_id = new_folder_id

# Upload file
file_metadata = {
    'name': 'my_file.csv',
    'parents': [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")}')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1