我想创建一个新目录并删除旧目录(如果存在)。我使用以下代码:
if os.path.isdir(dir_name):
shutil.rmtree(dir_name)
os.makedirs(dir_name)
Run Code Online (Sandbox Code Playgroud)
如果目录不存在,它会起作用。
如果目录确实存在并且程序正常运行,则会出错。(WindowsError:[错误 5] 访问被拒绝:'my_directory')
但是,如果目录已经存在并且程序在调试模式下逐行执行,它也可以工作。我想shutil.rmtree()并且makedirs()在他们的通话之间需要一些时间。
什么是正确的代码,以便它不会产生错误?
在 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6049 次 |
| 最近记录: |