使用Google-Drive-API移动文件
问题描述:
是否可以通过python的googleapiclient模块显式移动文件?我想创建下面的函数,给定一个文件,原来的路径和目标路径:使用Google-Drive-API移动文件
def move_file(service, filename, init_drive_path, drive_path, copy=False):
"""Moves a file in Google Drive from one location to another.
service: Drive API service instance.
filename (string): full name of file on drive
init_drive_path (string): initial file location on Drive
drive_path (string): the file path to move the file in on Drive
copy (boolean): file should be saved in both locations
Returns nothing.
"""
目前,我已通过手动下载该文件,然后将其重新上传到所需的位置执行这一点,但是这是不适用于大文件,无论如何,它似乎都是一种解决方法。
Here's the documentation有关google-drive-api上可用的方法。
编辑请参见下面的解决方案:
答
Found it here.你只需要检索的文件和文件夹ID,然后使用更新方法。如果你想保留文件的副本旧的文件夹(S)的remove_parents参数可以被排除
file_id = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ'
folder_id = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E'
# Retrieve the existing parents to remove
file = drive_service.files().get(fileId=file_id,
fields='parents').execute();
previous_parents = ",".join(file.get('parents'))
# Move the file to the new folder
file = drive_service.files().update(fileId=file_id,
addParents=folder_id,
removeParents=previous_parents,
fields='id, parents').execute()
(注意我没有将我的基本辅助功能_getFileId和_getFolderId)所以我原来的功能会看例如:
def move_file(service, filename, init_drive_path, drive_path, copy=False):
"""Moves a file in Google Drive from one location to another.
service: Drive API service instance.
'filename' (string): file path on local machine, or a bytestream
to use as a file.
'init_drive_path' (string): the file path the file was initially in on Google
Drive (in <folder>/<folder>/<folder> format).
'drive_path' (string): the file path to move the file in on Google
Drive (in <folder>/<folder>/<folder> format).
'copy' (boolean): file should be saved in both locations
Returns nothing.
"""
file_id = _getFileId(service, filename, init_drive_path)
folder_id = _getFolderId(service, drive_path)
if not file_id or not folder_id:
raise Exception('Did not find file specefied: {}/{}'.format(init_drive_path, filename))
file = service.files().get(fileId=file_id,
fields='parents').execute()
previous_parents = ",".join(file.get('parents'))
if copy:
previous_parents = ''
file = service.files().update(fileId=file_id,
addParents=folder_id,
removeParents=previous_parents,
fields='id, parents').execute()