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

Python’s os.rmdir() only works on empty the directories, however shutil.rmtree() doesn’t care (even if there are subdirectories) which makes it very similar to the Linux rm -rf command.

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)