それマグで!

知識はカップより、マグでゆっくり頂きます。 takuya_1stのブログ

習慣に早くから配慮した者は、 おそらく人生の実りも大きい。

Python で空じゃないディレクトリを削除する方法

Pythonでディレクトリを削除しようとすると os.rmdir だけど

import os 

os.rmdir("/path/to/not_empty_dir")

実行すると not empty で止まる。

OSError: [Errno 39] Directory not empty:

ま、当然なんだけど。

消す方法

  • shell をcall して rm -rf path/to/dir する
  • shutil.rmtree を使う

シェル経由で rmdir 呼び出すのはまぁ、想像つくんだけど、ruby の FileUtil に相当するものがないのか調べたら、shutilがそれらしい。

shutil.rmtreeの場合

コレが確実っぽい

import shutil
shutil.rmtree("path/to/dir")

これで、確実に作業用ディレクトリを捨てられる。

参考資料

http://stackoverflow.com/questions/13766513/how-to-do-force-remove-in-python-like-rm-rf-on-linux