Python中tempfile库删除临时目录时抛出错误求助
临时目录无法自动删除的PermissionError问题
使用tempfile.TemporaryDirectory创建临时目录,复制文件后上传至Google Drive,上传完成执行quit(),但退出with代码块时临时目录无法自动删除,抛出PermissionError等错误,其余功能正常。
原代码
with TemporaryDirectory(dir='.', prefix="pyGDriveUpload_temp_") as tempDir: tempDir = tempDir + '\\' for copyFile in selectedFiles: createdTime = os.path.getctime(copyFile) fileName = os.path.basename(copyFile) shutil.copy2(copyFile, tempDir + (fileName)) setctime(tempDir + fileName, createdTime) uploadList = os.listdir(tempDir) # Upload uploadCount = len(uploadList) progress = 1 print("\nUploading " + "0" + "/" + str(uploadCount), end='\r') for uploadFile in uploadList: getTime = datetime.datetime.fromtimestamp(os.path.getctime(tempDir + uploadFile)) ctime = getTime.isoformat('T') + 'Z' if FolderHasBeenProvidedByUser: gfile = drive.CreateFile({'parents': [{'id': gFolderID}], 'title': uploadFile, 'createdDate': ctime, 'modifiedDate': ctime}) elif not FolderHasBeenProvidedByUser: gfile = drive.CreateFile({'title': uploadFile, 'createdDate': ctime, 'modifiedDate': ctime}) # Read file and set it as the content of this instance. gfile.SetContentFile(os.path.abspath(tempDir) + '\\' + uploadFile) gfile.Upload() # Upload the file. print("Uploading " + str(progress) + "/" + str(uploadCount), end='\r') progress += 1 print("Files Successfully Uploaded! Closing...", end='') winsound.PlaySound("C:\Windows\Media\Windows Balloon.wav", winsound.SND_ALIAS) sleep(1.5) quit()
报错回溯
Traceback (most recent call last): File "C:\Users\mjc01\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 617, in _rmtree_unsafe os.unlink(fullname) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: '.\\pyGDriveUpload_temp_rhz30vlz\\video.mkv' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\mjc01\AppData\Local\Programs\Python\Python310\lib\tempfile.py", line 843, in onerror _os.unlink(path) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: '.\\pyGDriveUpload_temp_rhz30vlz\\video.mkv' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\mjc01\Documents\My Better Scripting\programs\final\Google Drive Uploader\pythonGDriveUpload.py", line 72, in <module> with TemporaryDirectory(dir='.', prefix="pyGDriveUpload_temp_") as tempDir: File "C:\Users\mjc01\AppData\Local\Programs\Python\Python310\lib\tempfile.py", line 869, in __exit__ self.cleanup() File "C:\Users\mjc01\AppData\Local\Programs\Python\Python310\lib\tempfile.py", line 873, in cleanup self._rmtree(self.name, ignore_errors=self._ignore_cleanup_errors) File "C:\Users\mjc01\AppData\Local\Programs\Python\Python310\lib\tempfile.py", line 855, in _rmtree _shutil.rmtree(name, onerror=onerror) File "C:\Users\mjc01\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 749, in rmtree return _rmtree_unsafe(path, onerror) File "C:\Users\mjc01\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 619, in _rmtree_unsafe onerror(os.unlink, fullname, sys.exc_info()) File "C:\Users\mjc01\AppData\Local\Programs\Python\Python310\lib\tempfile.py", line 846, in onerror cls._rmtree(path, ignore_errors=ignore_errors) File "C:\Users\mjc01\AppData\Local\Programs\Python\Python310\lib\tempfile.py", line 855, in _rmtree _shutil.rmtree(name, onerror=onerror) File "C:\Users\mjc01\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 749, in rmtree return _rmtree_unsafe(path, onerror) File "C:\Users\mjc01\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 600, in _rmtree_unsafe onerror(os.scandir, path, sys.exc_info()) File "C:\Users\mjc01\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 597, in _rmtree_unsafe with os.scandir(path) as scandir_it: NotADirectoryError: [WinError 267] The directory name is invalid: '.\\pyGDriveUpload_temp_rhz30vlz\\video.mkv'
解决方案
- 禁止修改
tempDir原变量:TemporaryDirectory返回的路径对象被tempDir = tempDir + '\\'修改后,清理逻辑会使用错误的路径。改用os.path.join拼接文件路径,避免手动修改原变量。 - 释放Google Drive文件句柄:上传完成后调用
gfile.Close(),确保Windows系统下文件不再被占用。 - 调整
quit()执行时机:将quit()放在with代码块外部,保证临时目录先完成清理再退出程序。
修改后的代码
import os from tempfile import TemporaryDirectory import shutil import datetime import winsound from time import sleep with TemporaryDirectory(dir='.', prefix="pyGDriveUpload_temp_") as tempDir: for copyFile in selectedFiles: createdTime = os.path.getctime(copyFile) fileName = os.path.basename(copyFile) dest_path = os.path.join(tempDir, fileName) shutil.copy2(copyFile, dest_path) setctime(dest_path, createdTime) uploadList = os.listdir(tempDir) uploadCount = len(uploadList) progress = 1 print(f"\nUploading 0/{uploadCount}", end='\r') for uploadFile in uploadList: file_path = os.path.join(tempDir, uploadFile) getTime = datetime.datetime.fromtimestamp(os.path.getctime(file_path)) ctime = getTime.isoformat('T') + 'Z' if FolderHasBeenProvidedByUser: gfile = drive.CreateFile({'parents': [{'id': gFolderID}], 'title': uploadFile, 'createdDate': ctime, 'modifiedDate': ctime}) else: gfile = drive.CreateFile({'title': uploadFile, 'createdDate': ctime, 'modifiedDate': ctime}) gfile.SetContentFile(file_path) gfile.Upload() gfile.Close() # 释放文件句柄 print(f"Uploading {progress}/{uploadCount}", end='\r') progress += 1 print("Files Successfully Uploaded! Closing...", end='') winsound.PlaySound("C:\\Windows\\Media\\Windows Balloon.wav", winsound.SND_ALIAS) sleep(1.5) quit()
内容的提问来源于stack exchange,提问作者Michael Cann
相关产品推荐
相关产品推荐

