2017-06-13 114 views
0

我試圖用python在谷歌驅動器上創建一個文件夾結構。我已經檢查過所有文檔和所有類似的stackoverflow問題,但它不起作用。PyDrive - 谷歌驅動器API - 創建文件夾樹

的文件夾結構,我想創造的東西就像

2017 ----06 --------13 --------14

我沒在任何其他地方比根目錄中創建一個文件夾。佈局是平坦的,我不明白爲什麼。

# this method should create a directory tree, from a string like '2017/06/14' 
def create_drive_folder(path): 
    # this method should create a folder with the given parents 
    # at first it is called with root as parent, for the 2017 folder 
    # and when the 06 folder should be created it gets [root and the successfully created 2017 folder id] 
    def create_drive_folder_level(filename, parents): 
     dirs = drive.ListFile(
      {'q': "'{}' in parents and trashed=false and mimeType='application/vnd.google-apps.folder'".format(
       parents[-1]['id'])}) 

     try: 
      # this will give me the parent folder, if it exists 
      current = [x for x in list(dirs)[0] if x['title'] == filename][0] 
     except HttpError: 
      current = None 
     except IndexError: 
      current = None 
     if not current: 
      meta = {'title': filename, 'parents': [x['id'] for x in [parents[-1]], 
        'mimeType': 'application/vnd.google-apps.folder'} 
      current = drive.CreateFile(meta) 
      current.Upload({'convert': True}) 
      return current 
     return current 

    path = path.split('/') 
    p = [dict(id='root')] 
    for i in range(len(path)): 
     p.append(create_drive_folder_level(path[i], p)) 

create_drive_folder('2017/06/14') 

UPDATE:

此代碼生成的輸出:

{'title': '2017', 'parents': ['root'], 'mimeType': 'application/vnd.google-apps.folder'} 
GoogleDriveFile({'title': '2017', 'parents': [{'kind': 'drive#parentReference', 'id': '0AC4TRMtjeM-PUk9PVA', 'isRoot': True}], 'mimeType': 'application/vnd.google-apps.folder', 'kind': 'drive#file', 'id': '0By4TRMtjeM-PRjNPT0pXaFpxY2s', ...}) 

{'title': '06', 'parents': ['0By4TRMtjeM-PRjNPT0pXaFpxY2s'], 'mimeType': 'application/vnd.google-apps.folder'} 
GoogleDriveFile({'title': '06', 'parents': [{'kind': 'drive#parentReference', 'id': '0AC4TRMtjeM-PUk9PVA', 'isRoot': True}], 'mimeType': 'application/vnd.google-apps.folder', 'kind': 'drive#file', 'id': '0By4TRMtjeM-PQUs0OWZ0VFlLTmM', ...}) 

{'title': '14', 'parents': ['0By4TRMtjeM-PQUs0OWZ0VFlLTmM'], 'mimeType': 'application/vnd.google-apps.folder'} 
GoogleDriveFile({'title': '14', 'parents': [{'kind': 'drive#parentReference', 'id': '0AC4TRMtjeM-PUk9PVA', 'isRoot': True}], 'mimeType': 'application/vnd.google-apps.folder', 'kind': 'drive#file', 'id': '0By4TRMtjeM-PN2o4MVplZERiUzA', ...}) 

在我看來,那我給正確的ID-S,創建子目錄時。佈局仍然變得平坦。爲什麼?

+0

你有任何錯誤日誌? – abielita

+0

我不知道。只有我提到的這些。 –

回答

0

我真的設法找到解決方案。問題是,父母必須是字符串,而不僅僅是字符串ID。 因此,而不是:

{'title': '06', 'parents': ['0By4TRMtjeM-PRjNPT0pXaFpxY2s']}

它應該是:

{'title': '06', 'parents': [{'id': '0By4TRMtjeM-PRjNPT0pXaFpxY2s'}]}

相關問題