alfredodeza
alfredodeza

Reputation: 5188

Removing dir contents from single file system in Python

The rm command allows you to do something like this:

rm -rf --one-file-system /path/to/dir/

And it will error out (skipping removal) if the contents of that dir have other file systems mounted in them.

Is there a module in Python that allows me to specify a similar behavior? If not, what would be the alternative to enforce such a constraint?

Upvotes: 1

Views: 276

Answers (1)

abarnert
abarnert

Reputation: 365717

There is no module that does this for you; you'll have to write it yourself.

But the os module provides everything you need to write it.*

First, os.walk can walk an entire directory tree. You can os.stat each directory and either skip those whose st_dev is different from the root's, or you can os.path.ismount each directory and skip those that are true.

This is almost exactly what rm is doing under the covers, except that of course it's using fts (or one of its predecessors, on older systems) rather than a Python function.

There are two tricky bits.

First, unlike fts and similar functions, os.walk doesn't stat the files (or, worse, it does stat the files, but doesn't give you the results), so you have to call os.stat explicitly on each dirname. (Or use a third-party module like scandir, betterwalk, py-fts, etc.)

Second, you have to go top-down to prune the walk (in top-down mode, if you remove dirs from the dirnames argument, walk will not recurse into them), but you have to go bottom-up to remove the files before removing the directories. With APIs like fts, which allow both pre-visiting and post-visiting in the same traversal, this isn't a problem, but os.walk makes you choose one or the other.

But this should be enough for you to get started on this. If you get stuck, you can always ask a new question.


* Well, os and os.path.

Upvotes: 2

Related Questions