Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 842
sara Avatar asked May 03 '17 09:05

sara


People also ask

How do you remove a directory and all of its files?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.

How do you delete a directory containing a file in Python?

remove() method can be used to delete a specific file, and the os. rmdir() method can be used to remove an empty directory. In addition, you can use the shutil. rmtree() method to delete a folder that contains one or more files.

How do I delete multiple files in a directory in Python?

To delete multiple files, just loop over your list of files and use the above os. rmdir() function. To delete a folder containing all files you want to remove have to import shutil package. Then you can remove the folder as follows.


1 Answers

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") 
like image 161
Kallz Avatar answered Oct 05 '22 18:10

Kallz