【问题标题】:Delete google drive files by extension with PyDrive使用 PyDrive 按扩展名删除 google drive 文件
【发布时间】:2021-05-06 18:48:39
【问题描述】:

我正在尝试从 Google 驱动器文件夹中删除所有扩展名为“.pdf”的文件。 API身份验证一切正常,我可以上传文件。问题在于删除。

我在这里上传

upload_file = 'Test1.pdf'
gfile = drive.CreateFile({'parents': [{'id': '11SsSKYEATgn_VWzSb-8RjRL-VoIxvamC'}]})
gfile.SetContentFile(upload_file)
gfile.Upload()

这里我尝试删除

delfile = drive.CreateFile({'parents': [{'id': '11SsSKYEATgn_VWzSb-8RjRL-VoIxvamC'}]})
filedel = "*.pdf"
delfile.SetContentFile(filedel)
delfile.Delete()

错误:

Traceback (most recent call last):
  File "C:/Users/linol/Documents/ProjetoRPA-Python/RPA-TESTE.py", line 40, in <module>
    delfile.SetContentFile(filedel)
  File "C:\Users\linol\Documents\ProjetoRPA-Python\venv\lib\site-packages\pydrive\files.py", line 175, in SetContentFile
    self.content = open(filename, 'rb')
OSError: [Errno 22] Invalid argument: '*.pdf'

【问题讨论】:

  • 为什么不启动google colab,连接到驱动器并运行!find '/content/drive/MyDrive' -type f -name '*.pdf' -delete
  • 以上代码只是近 100 行代码的一部分。我正在使用 PyCharm

标签: python google-drive-api pydrive


【解决方案1】:

我相信你的目标和你目前的情况如下。

  • 您要删除特定文件夹中的 PDF 文件。
  • 您想使用 pydrive for python 来实现这一点。
  • 您已经能够使用 Drive API 为 Google Drive 获取和放置值。

在这种情况下,我想提出以下流程。

  1. 从特定文件夹中检索 PDF 文件的文件列表。
  2. 使用文件列表删除文件。

当上述流程反映到脚本时,变成如下。

示例脚本:

请将###修改为您的文件夹ID。

# 1. Retrieve file list of PDF file from the specific folder.
fileList = drive.ListFile({'q': "'###' in parents and mimeType='application/pdf'"}).GetList()

# 2. Delete the files using the file list.
for e in fileList:
    drive.CreateFile({'id': e['id']}).Trash()
    # drive.CreateFile({'id': e['id']}).Delete() # When you use this, the files are completely deleted. Please be careful this.
  • 此示例脚本使用 mimeType 检索文件。当您想使用文件名检索文件时,您也可以使用fileList = drive.ListFile({'q': "'###' in parents and title contains '.pdf'"}).GetList()
  • 重要提示:在此示例脚本中,当使用 Delete() 时,文件将从 Google Drive 中完全删除。所以首先,我建议使用Trash() 而不是Delete() 作为脚本测试。这样,文件不会被删除并移动到垃圾箱。至此,我认为您可以测试脚本。

注意:

  • 似乎 PyDrive 使用 Drive API v2。请注意这一点。

参考:

【讨论】:

  • 我做了上面的过程,研究了引用,代码没有产生错误,但没有删除文件。
  • 尝试打印(文件列表)时,终端没有返回任何内容
  • @Lino Costa 感谢您的回复。我带来的不便表示歉意。不幸的是,我无法复制您的情况。在我的环境中,当我测试上面的脚本时,我可以确认文件可以被删除。我为此道歉。从When trying a print (filelist), nothing returns in the terminal,在这种情况下,似乎没有检索到文件。我认为您当前问题的原因是由于此。那么,您能否再次确认您当前的脚本和文件夹?当 PDF 文件放入文件夹时,filelist 具有值。
  • @Lino Costa 例如,如果您的PDF文件没有application/pdf的mimeType,当您测试我已经提到的fileList = drive.ListFile({'q': "'###' in parents and title contains '.pdf'"}).GetList()时,您会得到什么结果?顺便问一下,您的文件夹是在共享云端硬盘还是您的 Google 云端硬盘中?
  • @Lino Costa 欢迎您。谢谢你让我知道。我很高兴你的问题得到了解决。如果您的问题得到解决,请按接受按钮。与您有相同问题的其他人也可以将您的问题作为可以解决的问题。我认为您的问题和解决方案将对他们有用。如果找不到按钮,请随时告诉我。 stackoverflow.com/help/accepted-answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-28
  • 2017-06-07
相关资源
最近更新 更多