[英]How to delete temp files using python?
So I tried to create a script that deletes all of your downloaded files and temp files.所以我尝试创建一个脚本来删除所有下载的文件和临时文件。 It deletes the downloaded files, but for the temp files I'm getting an error.
它会删除下载的文件,但对于临时文件,我收到了一个错误。
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.")
This is the code.这是代码。 After running it, the downloaded files are deleted but at the temp files I get this error:
运行后,下载的文件被删除,但在临时文件中出现此错误:
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'
If other processes are currently using the temporary files in C:\Windows\Temp
you'll get an error, because deleting currently used files could cause errors in those other processes.如果其他进程当前正在使用
C:\Windows\Temp
中的临时文件,您将收到错误消息,因为删除当前使用的文件可能会导致其他进程出错。
If you get a PermissionError
when you try to do this, just wrap it in a try/except so that it can continue deleting the rest of the files that aren't being used instead of crashing the program.如果您在尝试执行此操作时遇到
PermissionError
,只需将其包装在 try/except 中,以便它可以继续删除未使用的文件的 rest 而不是使程序崩溃。
Also know that deleting temp files, even if they aren't currently opened by another process, could still be looked up, so that might cause issues.还知道删除临时文件,即使它们当前没有被另一个进程打开,仍然可以查找,所以这可能会导致问题。
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.