1

As far I can tell, there are separate APIs to remove folders and files in Python (os.remove and os.rmdir or shutil.rmtree). Isn't there one function library that does it all, no question asked, or do I need to write my own function to do so?

In short, what is the python equivalent of rm -fr ?

Lolo
  • 3,935
  • 5
  • 40
  • 50
  • `shutil.rmtree` does `rm -fr` – PCM Jun 24 '21 at 09:54
  • So, in short python equivalent of `rm -fr` is `shutil.rmtree` – PCM Jun 24 '21 at 09:55
  • But why do you want function library other than `shutil.rmtree` – PCM Jun 24 '21 at 09:56
  • @PCM just tested it and rmtree returns: ´NotADirectoryError: [Errno 20] Not a directory: 'test'´ – Kerrim Jun 24 '21 at 09:57
  • of course, you need to put something like `C:/...` not test – PCM Jun 24 '21 at 09:58
  • As far as i know there is no function that does that but you could easily write one and use it in your code. – Kerrim Jun 24 '21 at 09:58
  • >touch xxx.x >python Python 3.7.9 Type "help", "copyright", "credits" or "license" for more information. >>> import shutil >>> shutil.rmtree("xxx.x") ...NotADirectoryError: [WinError 267] The directory name is invalid: 'xxx.x' >>> exit() – Lolo Jun 24 '21 at 09:58
  • So you want to remove files and folders using your cmd prompt or terminal ? – PCM Jun 24 '21 at 09:59
  • @Kerrim Yes, that's what I have for now. Just did not want to reinvent the wheel and would rather make sure I am not missing a library. Seems odd not to have that support natively. – Lolo Jun 24 '21 at 10:00
  • @PCM No, I simply showed using my terminal that rmtree doesn't work on files. I am asking if in a python script I can use a library function that will remove directories and files the same way. – Lolo Jun 24 '21 at 10:01
  • No, you can't but you can mix 2 func to remove files and folders – PCM Jun 24 '21 at 10:02
  • Have you heard about `os.unlink(path)` – PCM Jun 24 '21 at 10:02
  • What is the use case where you do not know if your target is a directory or a file? You should know – Chris_Rands Jun 24 '21 at 10:02
  • There doesn't exist such a function in python, linux rm -rf removes all files even if it has read-only permission. but shutil.rmtree doesn't do that see this answer – darth baba Jun 24 '21 at 10:03
  • Does this answer your question? https://stackoverflow.com/a/41789397/11647025 – crissal Jun 24 '21 at 10:06
  • @crissal The answer you point me to is essentially the function I wrote. I was wondering if I could avoid having a custom function do just that. Apparently not. Thank you. – Lolo Jun 24 '21 at 10:13
  • @Chris_Rands I know if what I want to remove is a file or directory. I have a long list of files and directories and was just hoping to deal with them the same way. – Lolo Jun 24 '21 at 10:16
  • 1
    Does this answer your question? [How to delete a file or folder?](https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder) – crissal Jun 24 '21 at 10:42

0 Answers0