【问题标题】:Cannot rename or move the file after downloading it from Google Drive using Drive API使用 Drive API 从 Google Drive 下载文件后无法重命名或移动文件
【发布时间】:2021-06-04 15:24:43
【问题描述】:

我正在尝试编写一个脚本,将图像上传到 Google Drive 并将图像的 OCR 版本下载为文本文件。

脚本运行给定文件夹中的每个图像文件并执行上述操作。文本文件首先保存为“just-temp.txt”,下载成功后,应将文件重命名为扩展名为 .txt 的图像文件的名称。然而,python 只是抛出PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 错误。

这是我的代码的基本版本:

inputdir = r'D:\test (Screenshots)'

for dirpath, dirs, files in os.walk(inputdir):
    files = [file for file in files if file.endswith(('.png','.jpg','.jpeg'))]

    for count, file in enumerate(files, start=1):

        thefile = os.path.join(dirpath,file)
        txtfile = os.path.splitext(thefile)[0] + ".txt"

        txtfile_tmp_name = dirpath + '\\' + 'just-temp' + '.txt'

        if os.path.isfile(txtfile):
           print ('File already processed.')
        else:
          print ('Processing file ...')

# Drive api code to upload image and download text file.

          mime = 'application/vnd.google-apps.document'
          res = service.files().create(
              body={
                  'name': thefile,
                  'mimeType': mime
              },
              media_body=MediaFileUpload(thefile, mimetype=mime, resumable=True)
           ).execute()

           downloader = MediaIoBaseDownload(
               io.FileIO(txtfile_tmp_name, 'wb'),
               service.files().export_media(fileId=res['id'], mimeType="text/plain")
           )
           done = False
           while done is False:
               status, done = downloader.next_chunk()

           service.files().delete(fileId=res['id']).execute()

# To rename "just-temp.txt" to the image file name

           os.rename(txtfile_tmp_name, txtfile)

           print ('File successfully processed.' + thefile)

Python 只是不断向我显示上述错误,而在执行 os.rename 命令之后什么也没有。

我想首先将文本文件命名为“just-temp.txt”,这样如果我的网络突然中断并且文件没有成功下载,下次运行脚本时会重新处理该文件。但是为什么它在一个简单的命令上显示错误。

【问题讨论】:

    标签: python google-drive-api


    【解决方案1】:

    在网上花了很多时间搜索类似问题后,我终于找到了解决方案。

    您需要将用于存储MediaFileUpload 对象的变量设置为无:

    所以只多写了一行代码:

    downloader = MediaIoBaseDownload(
                   io.FileIO(txtfile_tmp_name, 'wb'),
                   service.files().export_media(fileId=res['id'], mimeType="text/plain")
               )
               done = False
               while done is False:
                   status, done = downloader.next_chunk()
    
               service.files().delete(fileId=res['id']).execute()
    
               downloader = None
    
               os.rename(txtfile_tmp_name, txtfile)
    
    

    感谢answer:

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 2015-05-30
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      相关资源
      最近更新 更多