LoginSignup
2
0

More than 5 years have passed since last update.

shutilでファイル数が少ないフォルダを一括削除する

Posted at

クロール先のデータがまとまった量で欲しい場合は、中途半端に取得されたフォルダは逆に邪魔になるので一括で削除したい。使いやすいように関数にしてまとめました。

使用環境

windows10
Anaconda 3.6.1

shutil

shutilはpython標準ライブラリの一つ。高度なディレクトリ操作が可能。
[公式レファレンス]https://docs.python.jp/3/library/shutil.html

コード

delete_folder.py
import os
import shutil

#デフォルトでは実行フォルダ内の要素3つ以下のフォルダを削除
def delete_folder( directory_dir= os.getwsd() ,size=3):

    folder_list = os.listdir(directory_dir)
    folder_dir = [os.path.join(directory_dir,i) for i in folder_list if len(os.listdir(os.path.join(directory_dir,i))) <= size ]
    for folder in folder_dir:
        print(folder+'を削除します')
        shutil.rmtree(folder)

    print('完了')
2
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
2
0