How do I remove/delete a folder that is not empty?
import shutil
shutil.rmtree('/folder_name')
Standard Library Reference: shutil.rmtree.
By design, rmtree
fails on folder trees containing read-only files. If you want the folder to be deleted regardless of whether it contains read-only files, then use
shutil.rmtree('/folder_name', ignore_errors=True)
Remove directory which is not empty
There is a module for this called rimraf
(https://npmjs.org/package/rimraf). It provides the same functionality as rm -Rf
Async usage:
var rimraf = require("rimraf");
rimraf("/some/directory", function () { console.log("done"); });
Sync usage:
rimraf.sync("/some/directory");
How to delete a non-empty folder in Batch script?
For the previous answer, I checked the current Microsoft documentation about commands it has, and it does NOT say clearly that the del command will delete only files.
The command you need to recursively delete a folder, and all files OR folders it contains is:
rmdir [name of the folder] /s /q
Please note the "/s" and "/q" arguments, which have the same meaning as for the del command, but they come AFTER the name of the folder! This is what the command documentation shows, as you may read here.
But there are more possible reasons for the recursive directory deletion failing! If you try to delete a directory that has system files or hidden files, the rmdir command will fail. To solve this problem, you need to do more work. To quote the documentation pointed above:
You can't delete a directory that contains files, including hidden or system files. If you attempt to do so, the following message appears:
The directory is not empty
Use the dir /a command to list all files (including hidden and system files). Then use the attrib command with -h to remove hidden file attributes, -s to remove system file attributes, or -h -s to remove both hidden and system file attributes. After the hidden and file attributes have been removed, you can delete the files.
How to remove a directory? Is os.removedirs and os.rmdir only used to delete empty directories?
You should be using shutil.rmtree
to recursively delete directory:
import shutil
shutil.rmtree('/path/to/your/dir/')
Answer to your question:
Is
os.removedirs
andos.rmdir
only used to delete empty directories?
Yes, they can only be used to delete empty directories.
Below is the description from official Python document which clearly stats that.
os.rmdir(path, *, dir_fd=None)
Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised. In order to remove whole directory trees, shutil.rmtree() can be used.
os.removedirs(name)
Remove directories recursively. Works like
rmdir()
except that, if the leaf directory is successfully removed, removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example, os.removedirs('foo/bar/baz') will first remove the directory 'foo/bar/baz', and then remove 'foo/bar' and 'foo' if they are empty. Raises OSError if the leaf directory could not be successfully removed.
Cannot remove item. The directory is not empty
You could try the following:
Remove-Item -Force -Recurse -Path "$directoryPath\*"
Note when using the -Recurse
parameter with -Include
in Remove-Item
, it can be unreliable. So it's best to recurse the files first with Get-ChildItem
and then pipe into Remove-Item
. This may also help if you deleting large folder structures.
Get-ChildItem $directoryPath -Recurse | Remove-Item -Force
Removing a non empty directory programmatically in C or C++
You want to write a function (a recursive function is easiest, but can easily run out of stack space on deep directories) that will enumerate the children of a directory. If you find a child that is a directory, you recurse on that. Otherwise, you delete the files inside. When you are done, the directory is empty and you can remove it via the syscall.
To enumerate directories on Unix, you can use opendir()
, readdir()
, and closedir()
. To remove you use rmdir()
on an empty directory (i.e. at the end of your function, after deleting the children) and unlink()
on a file. Note that on many systems the d_type
member in struct dirent
is not supported; on these platforms, you will have to use stat()
and S_ISDIR(stat.st_mode)
to determine if a given path is a directory.
On Windows, you will use FindFirstFile()
/FindNextFile()
to enumerate, RemoveDirectory()
on empty directories, and DeleteFile()
to remove files.
Here's an example that might work on Unix (completely untested):
int remove_directory(const char *path) {
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;
if (d) {
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) {
int r2 = -1;
char *buf;
size_t len;
/* Skip the names "." and ".." as we don't want to recurse on them. */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
continue;
len = path_len + strlen(p->d_name) + 2;
buf = malloc(len);
if (buf) {
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf)) {
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(buf);
else
r2 = unlink(buf);
}
free(buf);
}
r = r2;
}
closedir(d);
}
if (!r)
r = rmdir(path);
return r;
}
python: delete non-empty dir
Use shutil.rmtree
:
import shutil
shutil.rmtree(path)
See the documentation for details of how to handle and/or ignore errors.
How do I remove a directory that is not empty?
There is no built-in function to do this, but see the comments at the bottom of http://us3.php.net/rmdir. A number of commenters posted their own recursive directory deletion functions. You can take your pick from those.
Here's one that looks decent:
function deleteDirectory($dir) {
if (!file_exists($dir)) {
return true;
}
if (!is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
return false;
}
}
return rmdir($dir);
}
You could just invoke rm -rf
if you want to keep things simple. That does make your script UNIX-only, so beware of that. If you go that route I would try something like:
function deleteDirectory($dir) {
system('rm -rf -- ' . escapeshellarg($dir), $retval);
return $retval == 0; // UNIX commands return zero on success
}
Related Topics
How to Start and Stop a Thread
Python: How to Make the Ansi Escape Codes to Work Also in Windows
How to Compare Multiple Variables to the Same Value
How to Handle Elements Inside Shadow Dom from Selenium
Python Regex Match or Operator
Python Pandas Max Value in a Group as a New Column
Correct Code to Remove the Vowels from a String in Python
Is It Ever Useful to Use Python's Input Over Raw_Input
Move an Object Every Few Seconds in Pygame
Why Do Some Functions Have Underscores "_" Before and After the Function Name
How to Remove/Delete a Folder That Is Not Empty
Best Way to Preserve Numpy Arrays on Disk
Update a Dataframe in Pandas While Iterating Row by Row