我正在尝试使用 python 在 google 驱动器上创建文件夹结构。我已经检查了所有文档以及所有类似的 stackoverflow 问题,但它不起作用。
我想创建的文件夹结构类似于
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')
更新:
此代码产生的输出:
{'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。布局仍然变得扁平。为什么?
最佳答案
我实际上设法找到了解决方案。问题是, parent 必须是字典,而不仅仅是字符串 ID。 所以代替:
{'标题': '06', ' parent ': ['0By4TRMtjeM-PRjNPT0pXaFpxY2s']}
应该是:
{'title': '06', 'parents': [{'id': '0By4TRMtjeM-PRjNPT0pXaFpxY2s'}]}
关于python - PyDrive - Google 驱动器 API - 创建文件夹树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44524537/