【发布时间】: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”,这样如果我的网络突然中断并且文件没有成功下载,下次运行脚本时会重新处理该文件。但是为什么它在一个简单的命令上显示错误。
【问题讨论】: