66

次のコードを使用すると、ディレクトリがまだ存在しない場合にディレクトリを作成できます。

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

このフォルダーは、プログラムがテキスト ファイルをそのフォルダーに書き込むために使用されます。しかし、次回プログラムを開いたときに、まったく新しい空のフォルダーから始めたいと思っています。

フォルダーが既に存在する場合、フォルダーを上書きする (そして同じ名前で新しいフォルダーを作成する) 方法はありますか?

4

6 に答える 6

107
import os
import shutil

dir = 'path_to_my_folder'
if os.path.exists(dir):
    shutil.rmtree(dir)
os.makedirs(dir)
于 2012-07-26T00:22:39.073 に答える
27
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ライブラリを見てみましょう。

于 2012-07-26T00:23:35.360 に答える
1

これは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)
于 2015-02-22T20:21:35.243 に答える
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
于 2012-07-26T00:26:31.383 に答える