エラー内容
Pythonアプリで以下のエラーが発生。
FileExistsError: [Errno 17] File exists: 'loggings'
原因と解決方法
BEFORE:
import os
os.makedirs("loggings")
# FileExistsError: [Errno 17] File exists: 'loggings'
AFTER:
import os
os.makedirs("loggings", exist_ok=True)
os.makedirs
関数は、既に存在するディレクトリを作成しようとするとFileExistsError
を発生させる。
これを防ぐためには、os.makedirs
関数のexist_ok
パラメータをTrue
に設定すると良いです。デフォルトではFalse
になっています。
True
にすると、ディレクトリが既に存在していてもエラーが発生せず、ディレクトリが存在しない場合のみ新たに作成されるようになりました。