首页 > 解决方案 > 出现错误后如何跳过删除文件?

问题描述

当我运行程序时,我需要创建删除临时文件夹中所有文件的进程,它说“该进程无法访问该文件,因为它正被另一个进程使用。”,所以我试图让它跳过该文件,如果它说,但它不起作用。我对python也很陌生。这是我的代码:

if event in ('Delete Temp'):
    while ("temp"):
        os.system('cmd /c "del /q/f/s %TEMP%\*"')

        if print('The process can not access the file because it is being used by another process.')
            pass

标签: pythonfile-iooperating-systemdelete-file

解决方案


您可以将删除命令包装在try/except块中,而不是os使用模块subprocess,以便在失败时抛出异常:

from subprocess import run
while condition:
    try:
        run('cmd /c "del /q/f/s %TEMP%\*"', shell=True, check=True)
    except CalledProcessError as ex:
        print(f"Failed to delete files. stdout: {ex.stdout}, stderr: {ex.stderr}, returncode: {ex.returncode}")

但是你应该改变你的while条件,你有一个无限循环 - (while "temp"将永远True


推荐阅读