I don't think there's a built-in function to do this, but you could easily do it yourself using
for dirpath, dirnames, filenames in os.walk(my_directory): # Remove regular files, ignore directories for filename in filenames: os.unlink(os.path.join(dirpath, filename))
If you want to do it in one line, and you have GNU find, outsource:
subprocess.check_call(["find", "-H", directory, "!", "-type", "d", "-delete"])
how about something like this:
import os def rm_files_in_tree(dir): for root, dirs, files in os.walk(dir): for file in files: path = os.path.abspath(os.path.join(root, file)) os.remove(path)
Python’s shutil module provides a function to delete all the contents of a directory i.e. ,In this article we will discuss how to delete an empty directory and also all contents of directory recursively i.e including contents of its sub directories.,Python’s os module provide a function to delete an empty directory i.e. ,Now suppose we want to delete all the contents of directory ‘/somedir/logs’ . But we have a file in logs directory that can not be deleted due to permission issues. Let’s pass a callback to handle the error
Python’s os module provide a function to delete an empty directory i.e.
Let’s use this to delete an empty directory,
import os # Delete an empty directory using os.rmdir() and handle exceptions try: os.rmdir('/somedir/log9') except: print('Error while deleting directory')
Python’s shutil module provides a function to delete all the contents of a directory i.e.
shutil.rmtree(path, ignore_errors = False, onerror = None)
import shutil dirPath = '/somedir/logs/'; # Delete all contents of a directory using shutil.rmtree() and handle exceptions try: shutil.rmtree(dirPath) except: print('Error while deleting directory')
Suppose we have a file in log directory that can not be deleted due to permission issues. So,
shutil.rmtree(dirPath, ignore_errors = True)
Archiving example with base_dir,An example that uses the ignore_patterns() helper:,Directory and files operations Platform-dependent efficient copy operations copytree example rmtree example ,Another example that uses the ignore argument to add a logging call:
>>> shutil.which("python") 'C:\\Python33\\python.EXE'
from shutil import copytree, ignore_patterns copytree(source, destination, ignore = ignore_patterns('*.pyc', 'tmp*'))
from shutil import copytree import logging def _logpath(path, names): logging.info('Working in %s', path) return  # nothing will be ignored copytree(source, destination, ignore = _logpath)
import os, stat import shutil def remove_readonly(func, path, _): "Clear the readonly bit and reattempt the removal" os.chmod(path, stat.S_IWRITE) func(path) shutil.rmtree(directory, onerror = remove_readonly)
>>> from shutil import make_archive >>> import os >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive')) >>> root_dir = os.path.expanduser(os.path.join('~', '.ssh')) >>> make_archive(archive_name, 'gztar', root_dir) '/Users/tarek/myarchive.tar.gz'
$ tar - tzvf / Users / tarek / myarchive.tar.gz drwx-- -- --tarek / staff 0 2010 - 02 - 01 16: 23: 40 . / -rw - r--r--tarek / staff 609 2008 - 06 - 09 13: 26: 54 . / authorized_keys - rwxr - xr - x tarek / staff 65 2008 - 06 - 09 13: 26: 54 . / config - rwx-- -- --tarek / staff 668 2008 - 06 - 09 13: 26: 54 . / id_dsa - rwxr - xr - x tarek / staff 609 2008 - 06 - 09 13: 26: 54 . / id_dsa.pub - rw-- -- -- - tarek / staff 1675 2008 - 06 - 09 13: 26: 54 . / id_rsa - rw - r--r--tarek / staff 397 2008 - 06 - 09 13: 26: 54 . / id_rsa.pub - rw - r--r--tarek / staff 37192 2010 - 02 - 06 18: 23: 10 . / known_hosts
After looking at the output, I realise I was going to delete the very important file, so I rewrite the code now correcting .rxt to .txt, commenting out the print and uncommenting the os.unlink(),These functions deletes the files/directories without sending to the recycle bin/trash. So these functions should be used really carefully,Let's say I want to delete all the text files in the folder, but instead of typing .txt I accidently typed .rxt,Instead of deleting permanantly, this module will send it to the trash of the operating system.
Problem Formulation: How to Remove a Directory in Python?,How to Delete a File or Folder in Python?,As pointed out here, this method works on symbolic links to directories in the directory to be removed.,You can also remove a directory in Windows if files are in a read only mode by using the following code from the Python docs:
So, if you run
rm -rf my_directory, it’ll forcefully remove
my_directory and all its child directories.
$ rm - rf my_directory
The most Pythonic way to
rm -rf is to use the function
shutil.rmtree() defined in the
shutil package. It takes one argument, the folder to be removed, and removes the folder recursively.
import shutil shutil.rmtree('my_directory')
If you generally want to suppress error messages, you can use the following command instead:
shutil.rmtree('my_directory', ignore_errors = True)
You can also remove a directory with all its content by using the
os.walk() method that goes over all files and folders in a given directory.
# CAUTION: top == '/' could delete all files on your disk! import os my_dir = '/my_directory' for root, dirs, files in os.walk(my_dir, topdown = False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name))
You can also remove a directory in Windows if files are in a read only mode by using the following code from the Python docs:
import os, stat, shutil def remove_readonly(func, path): os.chmod(path, stat.S_IWRITE) func(path) directory = 'my_dir' shutil.rmtree(directory, onerror = remove_readonly)
© 2022 Tech Notes Help
After more investigation, the following appears to work:
def del_rw(action, name, exc): os.chmod(name, stat.S_IWRITE) os.remove(name) shutil.rmtree(path, onerror = del_rw)
shutil.rmtree is used to delete directories that are not empty (remove tree).
import os import stat import shutil def del_ro_dir(dir_name): Remove Read Only Directories for (root, dirs, files) in os.walk(dir_name, topdown = True): os.chmod(root, # For user... stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | # For group... stat.S_IWGRP | stat.S_IRGRP | stat.S_IXGRP | # For other... stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH ) shutil.rmtree(dir_name) if __name__ == __main__: del_ro_dir(dir_name_here)
To delete a file only, you can use the following code:
import os import stat def rmv_rof(file_name): Remov Read Only Files if os.path.exists(file_name): os.chmod(file_name, stat.S_IWRITE) os.remove(file_name) else: print(The file does not exist.) rmv_rof(file_name_here)