I am most interested in the non-recursive case, but I am guessing others who might track this question would prefer seeing the recursive case.
Basically, we are aiming to accomplish:
rm -rf <target>
However, a system call would be an immature answer.
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.
Deleting file/dir using the os. rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.
The rm command removes complete directories, including subdirectories and files. The rmdir command removes empty directories.
Use the nftw()
(File Tree Walk) function, with the FTW_DEPTH
flag. Provide a callback that just calls remove()
on the passed file:
#define _XOPEN_SOURCE 500 #include <stdio.h> #include <ftw.h> #include <unistd.h> int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { int rv = remove(fpath); if (rv) perror(fpath); return rv; } int rmrf(char *path) { return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With