gpt4 book ai didi

python - 如何用 PyDrive 替换/更新 Google Drive 上的文件?

转载 作者:行者123 更新时间:2023-12-04 17:37:37 26 4
gpt4 key购买 nike

我的应用程序需要每天上传一些文件,更新那些已经存在的文件。

我知道如果我传递现有文件的 ID,它们将被更新,但我想知道是否有一些更聪明的解决方案。

def upload_file(path, folder, filename, drive):

if not os.path.exists(path):
print('Arquivo não encontrado: {}'.format(filename))
return



id_folder_destiny = get_id_from_gdrive(folder)
file_metadata = {'title': filename,
'parents': [{'kind': 'drive#fileLink',
'id': id_folder_destiny}]}
file = drive.CreateFile(file_metadata)

file.SetContentFile(path)
file.Upload()

上面的代码没有“搜索现有 ID”。

最佳答案

我发现更新 Google 驱动器文件的最佳解决方案是上传具有 drive.CreateFile 函数中指定 ID 的文件,如您所说。这是我下载然后覆盖特定文件的代码。

def upload_file_to_drive(file_id, local_path):
"""Overwrites the existing Google drive file."""
update_file = drive.CreateFile({'id': file_id})
update_file.SetContentFile(local_path)
update_file.Upload()

def download_drive_file(file_id, save_path):
"""Downloads an existing Google drive file."""
download_file = drive.CreateFile({'id': file_id})
download_file.GetContentFile(save_path)

与 OOP 类一起使用:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

def get_google_drive_auth(self):
"""Initilaizes the Google drive 'drive' object. """
gauth = GoogleAuth()

# Try to load saved client credentials
gauth.LoadCredentialsFile("path/to/your/credentials/file")

if gauth.credentials is None:
# Authenticate if they're not there
gauth.GetFlow()
gauth.flow.params.update({'access_type': 'offline'})
gauth.flow.params.update({'approval_prompt': 'force'})
gauth.LocalWebserverAuth()

elif gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
else:
# Initialize the saved creds
gauth.Authorize()

# Save the current credentials to a file
gauth.SaveCredentialsFile("path/to/your/credentials/file")

self.drive = GoogleDrive(gauth)

def upload_file_to_drive(self, file_id, local_path):
"""Overwrites the existing Google drive file."""
update_file = self.drive.CreateFile({'id': file_id})
update_file.SetContentFile(local_path)
update_file.Upload()

def download_drive_file(self,file_id, save_path):
"""Downloads an existing Google drive file."""
download_file = self.drive.CreateFile({'id': file_id})
download_file.GetContentFile(save_path) # Save Drive file as a local file

关于python - 如何用 PyDrive 替换/更新 Google Drive 上的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56082335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com