我正在尝试使用python在google驱动器上创建文件夹结构。我检查了所有文档和所有类似的stackoverflow问题,但它不起作用。
我想要创建的文件夹结构类似于
2017
----06
--------13
--------14
我没有设法在除root之外的任何其他位置创建文件夹。布局是平坦的,我不明白为什么。
# 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')
更新:
此代码生成的输出:
{'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。布局仍然平坦。为什么?
答案 0 :(得分:1)
我实际上设法找到了解决方案。问题是,父母必须是口头禅,而不仅仅是字符串ID。 所以而不是:
{'title': '06', 'parents': ['0By4TRMtjeM-PRjNPT0pXaFpxY2s']}
应该是:
{'title': '06', 'parents': [{'id': '0By4TRMtjeM-PRjNPT0pXaFpxY2s'}]}