Python OS 模块,删除文件夹

时间:2021-07-21 09:44:11

标签: python cmd

嘿伙计们为什么这行代码不返回任何内容。就像它一直在运行......它删除了我想要它删除的文件,但程序没有退出。 os.system('cmd /k rmdir /s /q {}'.format(path))

2 个答案:

答案 0 :(得分:1)

> cmd /?

/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains

试试 /c 或只是 os.system('<your code without cmd /c >')

这是因为参数 /k(keep) let cmd 保留而 /c(close) 不保留。

答案 1 :(得分:0)

调用 os.system 将只返回一个退出值。如果它卡住了 - 它可能正在等待文件锁定,例如该子目录中的 cmd shell 或打开的文件。

我建议使用带有 shell=True 的 subprocess.call(或检查调用),这将消除包装 cmd 调用。

不过,我会更进一步,建议使用 shutil.rmtree 函数递归删除目录。