使用驱动器 API 从 Google 驱动器下载文件后无法重命名或移动文件

Cannot rename or move the file after downloading it from Google Drive using Drive API

我正在尝试编写一个脚本,将图像上传到 Google 驱动器并将图像的 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”,这样如果我的互联网突然断线并且文件没有成功下载,下次我重新处理该文件运行 脚本。但是为什么它在一个简单的命令上显示错误。

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

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

所以只增加了一行代码:

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: