Skip to content Skip to sidebar Skip to footer

How To Remove A Directory Including All Its Files In Python?

I'm working on some Python code. I want to remove the new_folder including all its files at the end of program. Can someone please guide me how I can do that? I have seen different

Solution 1:

If you want to delete the file

import osos.remove("path_to_file")

but you can`t delete directory by using above code if you want to remove directory then use this

import osos.rmdir("path_to_dir")

from above command, you can delete a directory if it's empty if it's not empty then you can use shutil module

import shutil
shutil.rmtree("path_to_dir")

All above method are Python way and if you know about your operating system that this method depends on OS all above method is not dependent

import osos.system("rm -rf _path_to_dir")

Solution 2:

Solution 3:

Here's my Approach:

# function that deletes all files and then folderimport glob, os

defdel_folder(dir_name):
    
    dir_path = os.getcwd() +  "\{}".format(dir_name)
    try:
        os.rmdir(dir_path)  # remove the folderexcept:
        print("OSError")   # couldn't remove the folder because we have files inside itfinally:
        # now iterate through files in that folder and delete them one by one and delete the folder at the endtry:
            for filepath in os.listdir(dir_path):
                os.remove(dir_path +  "\{}".format(filepath))
            os.rmdir(dir_path)
            print("folder is deleted")
        except:
            print("folder is not there")

Solution 4:

use os.system("rm -rf" + whatever_path +" new_folder")

Post a Comment for "How To Remove A Directory Including All Its Files In Python?"