dayjournal memo

Total 975 articles!!

Python #005 - ディレクトリをファイルごと全て削除

Yasunori Kirimoto's avatar

Pythonでディレクトリをファイルごと全て削除したい時は下記のように記述します。


sample.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import shutil

if __name__ == '__main__':

    sample_dir = os.path.exists("./sample")

    if sample_dir == True:
        shutil.rmtree("./sample")
        print ("sampleディレクトリを削除しました")
    else:
        print ("sampleディレクトリは存在しません")

今回は、事前にsampleディレクトリを準備しました。


下記コマンドを実行すると、sampleディレクトリがファイルごと全て削除されます。


python sample.py


ディレクトリの有無:


sample_dir = os.path.exists("./sample")

ディレクトリをファイルごと全て削除:


shutil.rmtree("./sample")

shutilを利用するとディレクトリをファイルごと全て削除することができます。



book

Q&A