Подтвердить что ты не робот

Как переписать папку, если она уже существует при создании с помощью makedirs?

Следующий код позволяет мне создать каталог, если он еще не существует.

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

Папка будет использоваться программой для записи текстовых файлов в эту папку. Но я хочу начать с новой, пустой папки в следующий раз, когда откроется моя программа.

Есть ли способ переписать папку (и создать новую, с тем же именем), если она уже существует?

4b9b3361

Ответ 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!

Ответ 3

os.path.exists(dir) рекомендуется, но его можно избежать, используя ignore_errors

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

Ответ 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

Ответ 5

Вот 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)

Ответ 6

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