[英]How to delete temp files using python?
所以我尝试创建一个脚本来删除所有下载的文件和临时文件。 它会删除下载的文件,但对于临时文件,我收到了一个错误。
import os
import shutil
temp_dir = "C:\Windows\Temp"
downloads_dir = os.path.join(os.environ['USERPROFILE'], "Downloads")
quit = input("Do you want to delete all the downloads? (Press enter to continue)")
for file in os.listdir(downloads_dir):
file_path = os.path.join(downloads_dir, file)
if os.path.isdir(file_path):
shutil.rmtree(file_path)
else:
os.remove(file_path)
print("All the downloaded files were deleted.")
quit = input("Do you want to delete all the temp files? (Press enter to continue)")
for file in os.listdir(temp_dir):
file_path = os.path.join(temp_dir, file)
if os.path.isdir(file_path):
shutil.rmtree(file_path)
else:
os.remove(file_path)
print("All the temp files were deleted.")
这是代码。 运行后,下载的文件被删除,但在临时文件中出现此错误:
os.remove(file_path)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Windows\\Temp\\DESKTOP-0CR5QUA-20221230-0000.log'
如果其他进程当前正在使用C:\Windows\Temp
中的临时文件,您将收到错误消息,因为删除当前使用的文件可能会导致其他进程出错。
如果您在尝试执行此操作时遇到PermissionError
,只需将其包装在 try/except 中,以便它可以继续删除未使用的文件的 rest 而不是使程序崩溃。
还知道删除临时文件,即使它们当前没有被另一个进程打开,仍然可以查找,所以这可能会导致问题。
for file in os.listdir(temp_dir):
file_path = os.path.join(temp_dir, file)
try:
if os.path.isdir(file_path):
shutil.rmtree(file_path)
else:
os.remove(file_path)
except PermissionError:
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.