Issue 19642: shutil to support equivalent of: rm -f /dir/* (original) (raw)

Created on 2013-11-18 11:45 by ivan.radic, last changed 2022-04-11 14:57 by admin.

Messages (4)
msg203283 - (view) Author: Ivan Radic (ivan.radic) Date: 2013-11-18 11:45
Shutil supports deleting of files and directories but it offers no way to delete directory content (without deleting directory itself). Shell programming includes a lot of "rm -rf /dir" and "rm -f /dir/*", and there is no direct equivalent of these commands in Python. Educate me if I am wrong on this claim. Sure, I can write a quick for loop, and delete each subfile and subdirectory manually, but adding such ability to shutil would greatly enhance readability and simplicity of Python file handling scripts. Implementation could be as simply as : import os for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) (example taken from http://docs.python.org/2/library/os.html#os.walk)
msg203296 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2013-11-18 14:42
See also issue 13229. You can replicate 'rm -f' like this: for p in glob.glob('/dir/*'): os.remove(p) That doesn't seem worth an extra function. The annoying one to emulate is 'rm -rf /dir/*', because with the current shutil tools you have to make different calls depending on whether the object is a file or a directory. Pathlib doesn't help with that (it has no generic 'remove' method that applies to both directories and files), but it does make the iteration easier.
msg227589 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2014-09-26 07:18
Rather like this: for n in os.listdir(dirpath): p = os.path.join(dirpath, n) if os.path.isdir(p): shutil.rmtree(p) else: os.unlink(p)
msg227618 - (view) Author: Antoine Pitrou (pitrou) * (Python committer) Date: 2014-09-26 14:08
> "rm -rf /dir" Isn't it shutil.rmtree()? Am I missing something? > "rm -f /dir/*" So it should skip dotted files, or remove them?
History
Date User Action Args
2022-04-11 14:57:53 admin set github: 63841
2014-10-06 15:27:32 barry set nosy: + barry
2014-09-26 14:08:54 pitrou set messages: +
2014-09-26 07🔞39 serhiy.storchaka set nosy: + serhiy.storchakamessages: +
2014-09-25 19:37:34 berker.peksag set stage: needs patch
2013-11-22 20:52:39 eric.araujo set nosy: + eric.araujo
2013-11-18 14:42:47 r.david.murray set nosy: + r.david.murray, pitroumessages: + components: + Library (Lib), - IO
2013-11-18 11:49:52 serhiy.storchaka set nosy: + tarek, hynekversions: - Python 2.7
2013-11-18 11:45:26 ivan.radic create