使用 Python 和 PyDrive 在 google 驱动器上成功上传文件,但文件已损坏

Uploaded a File succesfully on google drive using Python with PyDrive but File is damaged

我正在尝试使用 Python(Pydrive) 将文件从我的计算机上传到 google 驱动器,它上传成功但已损坏且大小变为 0kb。

这是我的代码:

drive = GoogleDrive(gauth)
import glob, os
with open('C:\Users\New\Pictures\Screenshots\older\Screenshot.png', 'r') as file:
          fn = os.path.basename(file.name)
          file_drive = drive.CreateFile({"title": fn })
file_drive.Upload()
print('The file: ' + fn + ' has been uploaded')
print('Successful')

我做错了什么?我已经完成了认证部分,并且认证成功。

我已经查看了与此相关的答案,但没有得到我要找的答案。

  • 您想将 C:\Users\New\Pictures\Screenshots\older\Screenshot.png' 的文件上传到 Google Drive using pydrive with python.
  • 您已经可以使用云端硬盘 API。

如果我的理解是正确的,这个修改怎么样?

修改点:

  • 在你的脚本中,没有给出文件内容。

修改后的脚本:

请按如下方式修改您的脚本。

从:
with open('C:\Users\New\Pictures\Screenshots\older\Screenshot.png', 'r') as file:
          fn = os.path.basename(file.name)
          file_drive = drive.CreateFile({"title": fn })
file_drive.Upload()
到:
f = 'C:\Users\New\Pictures\Screenshots\older\Screenshot.png'  # Added
with open(f, 'r') as file:  # Modified
          fn = os.path.basename(file.name)
          file_drive = drive.CreateFile({"title": fn })
file_drive.SetContentFile(f)  # Added
file_drive.Upload()

参考文献:

如果这不是您想要的方向,我深表歉意。