[英]Cannot move a file across folders in google drive using PyDrive
我一直在嘗試使用 PyDrive 將文件從一個文件夾移動到我的谷歌驅動器中的另一個文件夾
file2 = drive.CreateFile({'id': <file id>})
file2['parents']=<destination folder id>
file2.Upload()
可以像這樣更改文件夾嗎? 如果不是,請建議使用 PyDrive 的任何替代方案。
自從提出這個問題已經有一段時間了,但是對於那些發生在這個問題上的人,這對我有用。 上面的解決方案對我不起作用,但是我將“kind”:“drive#fileLink”更改為“drive#parentReference”。
最終代碼看起來像;
file2 = drive.CreateFile({'id': <file id>})
file2['parents'] = [{"kind": "drive#parentReference", "id": <destination_id>}]
file2.Upload()
這將覆蓋文件的父信息,有效地模擬 Drive UI 中的“移動到”功能。
PyDrive 是 Google Drive api 的便捷包裝器,但似乎仍有一些方法無法按預期工作。
幸運的是,您仍然可以像這樣訪問這里提出的底層 google drive api 方法:
file_id = <file id>
new_parent = <new parent id>
files = drive.auth.service.files()
file = files.get(fileId= file_id, fields= 'parents').execute()
prev_parents = ','.join(p['id'] for p in file.get('parents'))
file = files.update( fileId = file_id,
addParents = new_parent,
removeParents = prev_parents,
fields = 'id, parents',
).execute()
我剛剛對此進行了測試,如果您使用的是 Web UI,則需要刷新頁面才能看到更改。
請注意,單個文件可以有多個父文件,這對於 jQuery 畫廊之類的東西非常有用。
什么實際有效:-
file1 = drive.CreateFile({'id': id_[0]})
file1.Upload()
file1['parents'] = [{"kind": "drive#parentReference", "id": "destination_folder_id"}]
file1.Upload()
解釋:-
第 1 行:-
file1 = drive.CreateFile({'id': 'file_id_here'}) #Create's GoogleDriveFile instance
上面的代碼行不會從您的文件中導入元數據,以便我們使用:-
第 2 行:-
file1.Upload() #gets metadata of the file
一旦檢索到元數據,我們將第 3 行中的父文件夾 ID 更改為目標文件夾 ID
第 3 行:-
file1['parents'] = [{"kind": "drive#parentReference", "id": "destination_folder_id"}]
現在再次上傳以保存更改(第 4 行),第 4 行:-
file1.Upload()# save and update changes
parents
數組不僅包含每個父文件夾的 ID,還包含一個具有附加信息的對象。
因此,您需要更改該行:
file2['parents'] += ['<parent ID>']
到:
file2['parents'].append({"kind": "drive#fileLink", "id": '<parent ID>'})
因此,完整的示例將是:
file2 = drive.CreateFile({'id': <file id>})
file2['parents'].append({"kind": "drive#fileLink", "id": '<parent ID>'})
file2.Upload()
您可以在此處找到使用文件夾的示例。
這是帶有工作代碼的 github 存儲庫的鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.