How to overwrite a folder if it already exists when creating it with makedirs?

半城伤御伤魂 提交于 2019-12-29 13:44:14

问题


The following code allows me to create a directory if it does not already exist.

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

The folder will be used by a program to write text files into that folder. But I want to start with a brand new, empty folder next time my program opens up.

Is there a way to overwrite the folder (and create a new one, with the same name) if it already exists?


回答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)

How about that? Take a look at shutil's Python library!




回答3:


os.path.exists(dir) check is recommended but can be avoided by using ignore_errors

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



回答4:


Just say

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



回答5:


try:
    os.mkdir(path)
except FileExistsError:
    pass



回答6:


Here's a EAFP (Easier to Ask for Forgiveness than Permission) version:

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)


来源:https://stackoverflow.com/questions/11660605/how-to-overwrite-a-folder-if-it-already-exists-when-creating-it-with-makedirs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!