我想创建一个新目录并删除旧目录(如果存在)。我使用以下代码:
if os.path.isdir(dir_name):
shutil.rmtree(dir_name)
os.makedirs(dir_name)
如果目录不存在,它将起作用。
如果目录确实存在并且程序正在正常运行,则会出错。 (WindowsError:[错误5]访问被拒绝:“ my_directory”)
但是,如果目录已经存在并且程序在调试模式下逐行执行,它也可以工作。我猜shutil.rmtree()
和makedirs()
在两次通话之间需要一些时间。
什么是正确的代码,这样它才不会产生错误?
python大神给出的解决方案
在Python中,仅在上一条语句完成后才执行一条语句,这就是解释器的工作方式。
我的猜测是shutil.rmtree
告诉文件系统删除某些目录树,并且在那一刻Python终止了该语句的工作-即使文件系统尚未删除完整的目录树也是如此。因此,如果目录树足够大,那么当Python到达os.makedirs(dir_name)
行时,该目录仍然可以存在。
一种更快的操作(比删除更快)是重命名目录:
import os
import tempfile
import shutil
dir_name = "test"
if (os.path.exists(dir_name)):
# `tempfile.mktemp` Returns an absolute pathname of a file that
# did not exist at the time the call is made. We pass
# dir=os.path.dirname(dir_name) here to ensure we will move
# to the same filesystem. Otherwise, shutil.copy2 will be used
# internally and the problem remains.
tmp = tempfile.mktemp(dir=os.path.dirname(dir_name))
# Rename the dir.
shutil.move(dir_name, tmp)
# And delete it.
shutil.rmtree(tmp)
# At this point, even if tmp is still being deleted,
# there is no name collision.
os.makedirs(dir_name)