1
0

【Python】「FileExistsError: [Errno 17] File exists: 'xxx'」エラーには`exist_ok=True`オプションを

Posted at

エラー内容

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にすると、ディレクトリが既に存在していてもエラーが発生せず、ディレクトリが存在しない場合のみ新たに作成されるようになりました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0