50

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 commands like os.rmdir but it only removes the path. Here is my code:

for files in sorted(os.listdir(path)):
  os.system("mv "+path+" new_folder")`

The code above will move a folder (called check) into new_folder. I want to remove that check folder from the new_folder.

bouteillebleu
  • 2,456
  • 23
  • 32
sara
  • 1,567
  • 4
  • 13
  • 21
  • 3
    Possible duplicate of [How do I remove/delete a folder that is not empty with Python?](http://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty-with-python) – Mike Scotty May 03 '17 at 09:36

4 Answers4

90

If you want to delete the file

import os
os.remove("path_to_file")

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

import os
os.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 os
os.system("rm -rf _path_to_dir")
Kallz
  • 3,244
  • 1
  • 20
  • 38
31

Just use shutil.rmtree

import shutil
shutil.rmtree(path)
Netwave
  • 40,134
  • 6
  • 50
  • 93
-1

Here's my Approach:

# function that deletes all files and then folder

import glob, os

def del_folder(dir_name):
    
    dir_path = os.getcwd() +  "\{}".format(dir_name)
    try:
        os.rmdir(dir_path)  # remove the folder
    except:
        print("OSError")   # couldn't remove the folder because we have files inside it
    finally:
        # now iterate through files in that folder and delete them one by one and delete the folder at the end
        try:
            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")
ans2human
  • 2,300
  • 1
  • 14
  • 29
-3

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

PMonti
  • 456
  • 3
  • 9
  • But I want to remove a folder that is inside another folder. – sara May 03 '17 at 10:17
  • I want to use something like. If os.path.exists() then remove – sara May 03 '17 at 10:19
  • the use os.system("rm -rf " + path + "/new_folder"). Also, the -f function does not throw an error if the folder does not exist so you are already set – PMonti May 03 '17 at 10:22
  • 1
    Better to use `shutil.rmtree` suggested in other answers. This answer opens up the possibility of arbitrary shell commands execution if the string `whatever_path` comes from untrusted input. – Odysseas Sep 20 '18 at 14:02