![](http://python-guide.work/wp-content/themes/cocoon-master/images/b-woman.png)
Pythonで
・フォルダを削除
できます!
![](http://python-guide.work/wp-content/themes/cocoon-master/images/b-woman.png)
フォルダの中にファイル等があっても、
まるっと削除できます!
コード
ここでは例として
・デスクトップ配下のフォルダ「folder_001」を削除
します。
※フォルダ「folder_001」の中にはファイルやサブフォルダが存在することとします。
![削除するフォルダ](https://python-guide.work/wp-content/uploads/2023/08/py_folder_rmdir_001.png)
import os
import shutil
# 削除するフォルダパス
dir = r"C:\Users\lunch\Desktop\folder_001"
try:
if os.path.exists(dir):
shutil.rmtree(dir)
except Exception as e:
print(e)
実行結果
フォルダを削除できました。
参考①
標準ライブラリ「os」モジュールの「rmdir」でもフォルダを削除できますが、こちらはフォルダの中身が空で無いとエラーとなります。
参考②
上記で使用した以下の詳細は、公式サイトをご確認ください。
●標準ライブラリ「shutil」モジュールの「rmtree」