📜  使用Python在 Google Drive 上上传文件

📅  最后修改于: 2022-05-13 01:55:00.061000             🧑  作者: Mango

使用Python在 Google Drive 上上传文件

在互联网的现代时代,大量的日常或与工作相关的任务是通过互联网执行的。泄露存储在设备上的数据可能会对个人/公司造成巨大伤害。考虑到恶意软件、病毒、蠕虫、特洛伊木马等数量的增加,静态数据的安全性已成为许多人关注的问题。

保护数据的最常见方法之一是创建数据备份。虽然备份确实为关键数据提供了一些保护,但它应该远离原始数据。这样即使包含原始数据的系统以某种方式受到损害,备份数据仍然是安全的。云存储是为实现这一目的而构建的技术。

任何拥有谷歌帐户的人都可以使用 15 GB 的免费云存储来存储他们的数据。这解决了异地备份的问题。但是每次上传文件数据可能有点麻烦。因此,为了简化该过程,我们将创建一个Python程序,该程序在目录中查找并将其中的任何文件上传到我们的 Google Drive 帐户。

为此,我们将使用pydrive库。这个模块没有预装Python。因此,要安装它,请在命令行中执行以下命令:

pip install pydrive

创建 OAuth 凭据

为了每次我们想向我们的谷歌账户上传一些数据时成功地验证它,我们需要创建一个 OAuth 凭证。

完成上述方法后,我们最终会得到一个名称类似于client_secret_(really long ID).json的文件。将文件重命名为“ client_secrets.json ”并将其放在将创建主Python程序的同一目录中。

代码

from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
   
# For using listdir()
import os
   
  
# Below code does the authentication
# part of the code
gauth = GoogleAuth()
  
# Creates local webserver and auto
# handles authentication.
gauth.LocalWebserverAuth()       
drive = GoogleDrive(gauth)
   
# replace the value of this variable
# with the absolute path of the directory
path = r"C:\Games\Battlefield"   
   
# iterating thought all the files/folder
# of the desired directory
for x in os.listdir(path):
   
    f = drive.CreateFile({'title': x})
    f.SetContentFile(os.path.join(path, x))
    f.Upload()
  
    # Due to a known bug in pydrive if we 
    # don't empty the variable used to
    # upload the files to Google Drive the
    # file stays open in memory and causes a
    # memory leak, therefore preventing its 
    # deletion
    f = None

上面的代码在执行时会执行你操作系统默认浏览器的一个实例。然后它会要求提供 pydrive 访问您的 Google Drive 帐户的权限。授予所有所需权限后,浏览器会显示一条消息

之后将启动将文件上传到 Google Drive 的过程。

使用上述程序时要记住的某些事项:-

  • 确保“client_secrets.json”与Python程序位于同一目录中
  • 目录(路径)不应包含其中的任何子目录
  • 您的 Google 云端硬盘应该有足够的空白空间以便合并新文件
  • 新文件将在 Google Drive 存储的根目录中创建