如果在使用makedirs创建文件夹时已经存在,如何覆盖该文件夹?

问题描述 投票:29回答:5

以下代码允许我创建一个目录(如果它尚不存在)。

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

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

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

python directory text-files overwrite
5个回答
50
投票
dir = 'path_to_my_folder'
if os.path.exists(dir):
    shutil.rmtree(dir)
os.makedirs(dir)

12
投票
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图书馆!


2
投票

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

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

1
投票

说啊

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

0
投票

EAFP (see about it here)版本

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)

0
投票
try:
    os.mkdir(path)
except FileExistsError:
    pass
© www.soinside.com 2019 - 2024. All rights reserved.