shutil.rmtree 在 Windows 上似乎不同步,因为我在以下代码中的第二行引发了目录已存在的错误
shutil.rmtree(my_dir)
os.makedirs(my_dir) #intermittently raises Windows error 183 - already exists
我们在 Windows 上的 .NET 中看到类似的问题 - see this question 。除了轮询看看文件夹是否真的消失之外,还有什么好的选择可以在 python 中处理这个问题吗?
最佳答案
如果您同意该文件夹仍然存在,并且您使用的是 Python 3,则可以执行 pass exist_ok=True
to os.makedirs
,并且它将忽略您尝试创建已存在的目录的情况:
shutil.rmtree(my_dir)
os.makedirs(my_dir, exist_ok=True)
如果做不到这一点,您将陷入轮询。循环运行代码(最好短暂 sleep 以避免损坏磁盘),直到 makedirs
完成且没有错误为止,不要结束循环:
import errno, os, shutil, time
while True:
# Blow away directory
shutil.rmtree(my_dir, ignore_errors=True)
try:
# Try to recreate
os.makedirs(my_dir)
except OSError as e:
# If problem is that directory still exists, wait a bit and try again
if e.winerror == 183:
time.sleep(0.01)
continue
# Otherwise, unrecognized error, let it propagate
raise
else:
# Successfully created empty dir, exit loop
break
在 Python 3.3+ 上,您可能可以更改:
except WindowsError as e:
# If problem is that directory still exists, wait a bit and try again
if e.errno == errno.EEXIST:
time.sleep(0.01)
continue
# Otherwise, unrecognized error, let it propagate
raise
只是:
except FileExistsError:
# If problem is that directory still exists, wait a bit and try again
time.sleep(0.01)
因为“文件存在”有一个特定的异常类型,您可以直接捕获它(并让所有其他 OSError
/WindowsError
异常不间断地传播)。
关于python - os.rmdir 或 Shutil.rmtree 是否保证或应该在 Windows 上同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47662422/