简体   繁体   English

Python:如何创建目录并在必要时覆盖现有目录?

[英]Python: How to create a directory and overwrite an existing one if necessary?

I want to create a new directory and remove the old one if it exists. 我想创建一个新目录并删除旧目录(如果存在)。 I use the following code: 我使用以下代码:

if os.path.isdir(dir_name):
    shutil.rmtree(dir_name)
os.makedirs(dir_name)

It works, if the directory does not exist. 如果目录不存在,它将起作用。

It errors if the directory does exist and the program in run normally. 如果目录确实存在并且程序正在正常运行,则会出错。 (WindowsError: [Error 5] Access is denied: 'my_directory') (WindowsError:[错误5]访问被拒绝:“ my_directory”)

However, it also works if the directory already exists and the program is executed in debug mode line by line. 但是,如果目录已经存在并且程序在调试模式下逐行执行,它也可以工作。 I guess shutil.rmtree() and makedirs() need some time in between their calls. 我猜shutil.rmtree()makedirs()在两次调用之间需要一些时间。

What is the correct code so that it doesn't create an error? 什么是正确的代码,这样它才不会产生错误?

In Python a statement is executed just when the previous statement have finished, thats how an interpreter works. 在Python中,仅在上一条语句完成后才执行一条语句,这就是解释器的工作方式。

My guess is that shutil.rmtree tell the filesystem to delete some directory tree and in that moment Python gives terminate the work of that statement -- even if the filesystem have not deleted the complete directory tree --. 我的猜测是shutil.rmtree告诉文件系统删除一些目录树,并且在那一刻Python给出了终止该语句的工作- 即使文件系统尚未删除完整的目录树也是如此 For that reason, if the directory tree is big enough, when Python get to the line os.makedirs(dir_name) the directory can still to exist. 因此,如果目录树足够大,则当Python到达os.makedirs(dir_name)该目录仍然可以存在。

A faster operation (faster than deleting) is to rename the directory: 一种更快的操作(比删除更快)是重命名目录:

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)

What about this? 那这个呢?

import shutil
import os

dir = '/path/to/directory'
if not os.path.exists(dir):
    os.makedirs(dir)
else:
    shutil.rmtree(dir)           
    os.makedirs(dir)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM