python - os.rmdir 或 Shutil.rmtree 是否保证或应该在 Windows 上同步?

标签 python

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/

相关文章:

python - 查找平均值与标准匹配的最大数据子集

python - 如何测试 python 中的两个对象是否相等?

python - 是否可以将 templateMatch 与二进制图像一起使用?我有一个错误

python - 使用 NumPy 更好的解决方案

Python/PIL仿射变换

python - 感知器学习算法不起作用

python - Pandas :在不重新排列数据帧的情况下对两行数据帧求和?

python - Python 2.7 如何比较列表中的项目

python - 事件未定义?

python - 在 python 中对插值函数 (interp1d) 进行积分