PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » File Handling » Python Remove/Delete Non-Empty Folder

Python Remove/Delete Non-Empty Folder

Updated on: December 28, 2021 | Leave a Comment

Are you getting OSError the directory is not empty error when deleting a non-empty folder using the os.rmdir() method? The os.rmdir() method is helpful to delete only empty folders.

In this article, we will use the shutil module to remove the non-empty directory or folder. The directory may have nested subdirectories many levels deep.

Shutil rmtree() to Delete Non-Empty Directory

The shutil module offers various methods to perform high-level operations on files and collections of files, such as file copying and file removal in Python.

Here we will see how to delete non-empty directories or folders in Python using the shutil.rmtree('path') function.

shutil.rmtree(path, ignore_errors=False, onerror=None)
  • The rmtree(‘path’) deletes an entire directory tree (including subdirectories under it).
  • The path must point to a directory (but not a symbolic link to a directory).
  • Set ignore_errors to True if you want to ignore the errors resulting from failed removal. Please set it to False to know the reason behind failed removal.
  • If the ignore_errors parameter is omitted, you need to handle errors using try-except by calling a handler specified by the onerror class.

Example

Let’s see how to delete a non-empty ‘account’ folder present in our drive.

import shutil

# remove old account directory
shutil.rmtree(r'E:\demos\files_demos\accounts_old')

Output:

Before deleting non empty folder
Before deleting the non-empty folder
After deleting non empty folder
After deleting the non-empty folder

Note:

By default, The shutil.rmtree() will fail to delete the directory containing any read-only files.

It will throw a PermissionError if a folder contains any read-only files. Set the optional argument ignore_errors to True to remove the remaining folder contents.

Example:

import shutil

# remove old account directory
shutil.rmtree(r'E:\demos\files_demos\accounts_old', ignore_errors=True)

Also, If files are added concurrently to this directory, then rmtree() will fail.

Delete Non-Empty Directory with Read-Only Files

  • As we discussed, The shutil.rmtree() will fail to delete the directory containing any read-only files.
  • Note: ignore_errors=True does not guarantee the directory will be deleted. There could be a PermissionError.
  • If you set ignore_errors to True, it will delete all other files except read-only files from a directory. (Directory is still present but only with read-only files).
  • Set ignore_errors to False to know the reasons behind failed removals.

Use the onerror parameter of a shutil.rmtree() function to delete an entire directory that contains some read-only files.

We need to write a custom function and assign it to the onerror parameter. This custom function uses the onerror callback to clear the read-only bit from a read-only file and again reattempt the remove.

Example:

import os
import shutil
import stat

# remove directory with read-only files
def rm_dir_readonly(func, path, _):
    "Clear the readonly bit and reattempt the removal"
    os.chmod(path, stat.S_IWRITE)
    func(path)

shutil.rmtree(r'E:\demos\files_demos\accounts_old', onerror=rm_dir_readonly)

Filed Under: Python, Python File Handling

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python File Handling

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

Posted In

Python Python File Handling
TweetF  sharein  shareP  Pin

Python File Handling

  • File Handling In Python
  • Create File in Python
  • Open a File in Python
  • Read File in Python
  • Write to File in Python
  • Python File Seek
  • Rename Files in Python
  • Delete Files in Python
  • Copy Files in Python
  • Move Files in Python
  • List Files in a Directory
  • File Handling Quiz

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com