【问题标题】:How to overwrite a folder if it already exists when creating it with makedirs?使用makedirs创建文件夹时如何覆盖已存在的文件夹?
【发布时间】:2012-07-24 12:38:13
【问题描述】:

下面的代码允许我创建一个不存在的目录。

dir = 'path_to_my_folder'
if not os.path.exists(dir):
    os.makedirs(dir)

程序将使用该文件夹将文本文件写入该文件夹。但是我想在下次打开程序时从一个全新的空文件夹开始。

如果文件夹已经存在,有没有办法覆盖(并创建一个同名的新文件夹)?

【问题讨论】:

  • 应该注意,尽管这对您来说可能并不重要,但这里的所有答案都有竞争条件(虽然实际上不可能完全消除它们,但您可以做得更好,通过使用 EAFP)。

标签: python directory text-files overwrite


【解决方案1】:
import os
import shutil

dir = 'path_to_my_folder'
if os.path.exists(dir):
    shutil.rmtree(dir)
os.makedirs(dir)

【讨论】:

    【解决方案2】:
    import os
    import shutil
    
    path = 'path_to_my_folder'
    if not os.path.exists(path):
        os.makedirs(path)
    else:
        shutil.rmtree(path)           # Removes all the subdirectories!
        os.makedirs(path)
    

    那怎么样?看看shutilPython 库!

    【讨论】:

    • 这也可以。但这是一个相当常见的模块吗?这段代码需要在很多机器上实现..
    • @ShankarKumar 是的。 shutil 是自 Python 2.4 以来 Python 的内置库的一部分。我个人认为shutilos 更好,因为它确实带来了一些简化。
    • 非常感谢,兄弟!裂纹
    【解决方案3】:

    建议使用os.path.exists(dir)检查,但可以通过使用ignore_errors来避免

    dir = 'path_to_my_folder'
    shutil.rmtree(dir, ignore_errors=True)
    os.makedirs(dir)
    

    【讨论】:

    • 为什么推荐os.path.exists(dir)os.path.exists(dir) 与您的方法相比有什么优势吗?
    • @Ali_Sh Python 中的惯用做法“请求原谅比请求许可更容易”。这里 ignore_errors 也是一样的。
    • @Ali_Sh, ignore_errors 忽略所有错误,而不仅仅是丢失目录错误。
    【解决方案4】:

    随便说说

    dir = 'path_to_my_folder'
    if not os.path.exists(dir): # if the directory does not exist
        os.makedirs(dir) # make the directory
    else: # the directory exists
        #removes all files in a folder
        for the_file in os.listdir(dir):
            file_path = os.path.join(dir, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path) # unlink (delete) the file
            except Exception, e:
                print e
    

    【讨论】:

    • 谢谢,这很好用!你介意解释一下它背后的逻辑吗?我是初学者,所以我想尽可能多地学习!
    • 如果您尝试删除的目录中有子目录,这将失败。然后你想打电话给os.walk 来解决这个问题。更简单的解决方案是使用shutil.rmtree
    • 那会不受竞争条件的影响吗?
    【解决方案5】:
    try:
        os.mkdir(path)
    except FileExistsError:
        pass
    

    【讨论】:

    • 这不会覆盖目录。如果目录不存在,它只会创建目录。
    【解决方案6】:

    这是EAFP(请求宽恕比请求许可更容易)版本:

    import errno
    import os
    from shutil import rmtree
    from uuid import uuid4
    
    path = 'path_to_my_folder'
    temp_path = os.path.dirname(path)+'/'+str(uuid4())
    try:
        os.renames(path, temp_path)
    except OSError as exception:
        if exception.errno != errno.ENOENT:
            raise
    else:
        rmtree(temp_path)
    os.mkdir(path)
    

    【讨论】:

    • 欢迎来到堆栈溢出!这是作为您的第一个答案来找我审查的。当用公认的答案回答一个老问题时,值得强调的是您要添加到现有解决方案中的内容。在这种情况下 - 你能解释为什么你认为这段代码不受竞争条件的影响吗?例如 - 如果在调用 glob.iglob() 后将文件写入目录会发生什么 - 您能否描述您的解决方案较少受竞争条件影响的原因?另外:您可能会考虑解释 EAFP 代表什么。 注意,由于原始错误,我重新发布了编辑过的评论
    • @JRichardSnape 是的,你是对的,这段代码不能免受竞争条件的影响。新版本,在我看来,满足了这个要求
    • 我认为这样做会更容易try: os.mkdir(path) except FileExistsError: shutil.rmtree(path) os.mkdir(path)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 2021-08-15
    • 2015-07-25
    • 2014-02-09
    • 1970-01-01
    • 2011-06-21
    • 2013-06-24
    相关资源
    最近更新 更多