close

How to check existence of a folder and then remove it?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to check existence of a folder and then remove it in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to check existence of a folder and then remove it?

  1. How to check existence of a folder and then remove it?

    os.rmdir() only works if the directory is empty, however shutil.rmtree() doesn't care (even if there are subdirectories). It's also more portable than using the rm command via os.system().

  2. check existence of a folder and then remove it

    os.rmdir() only works if the directory is empty, however shutil.rmtree() doesn't care (even if there are subdirectories). It's also more portable than using the rm command via os.system().

Method 1

os.rmdir() only works if the directory is empty, however shutil.rmtree() doesn’t care (even if there are subdirectories). It’s also more portable than using the rm command via os.system().

import os
import shutil

dirpath = os.path.join('dataset3', 'dataset')
if os.path.exists(dirpath) and os.path.isdir(dirpath):
    shutil.rmtree(dirpath)

Modern approach

In Python 3.4+ you can do same thing using the pathlib module to make the code more object-oriented and readable:

from pathlib import Path
import shutil

dirpath = Path('dataset3') / 'dataset'
if dirpath.exists() and dirpath.is_dir():
    shutil.rmtree(dirpath)

Method 2

os.remove() is to remove a file.

os.rmdir() is to remove an empty directory.

shutil.rmtree() is to delete a directory and all its contents.

import os

folder = "dataset3/"

# Method 1
for files in os.listdir(folder):
    if files == "dataset":
        os.remove(folder + "dataset")

# Method 2
if os.path.exists(folder + "dataset"):
    os.remove(folder + "dataset")

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read