Why doesn't os.remove work on directories?

Ben Finney ben+python at benfinney.id.au
Wed Dec 23 00:02:55 EST 2015


Random832 <random832 at fastmail.com> writes:

> This is surprising to anyone accustomed to the POSIX C remove
> function, which can remove either files or directories.  Is there
> any known rationale for this decision?

No, I don't know a rationale for implementing it this way.

I expect the explanation will be “mere historical accident”. My
evidence-free reconstruction of the events leading to the current state
of play:

1.  ‘os.unlink’ implemented, using C ‘unlink(3)’. Because ‘unlink(2)’
    on a directory will cause an error, Python raises OSError for this.

2.  ‘os.remove’ implemented; “This is identical to the unlink() function
    documented below.”.

3.  Backward compatibility concerns (existing code might depend on
    ‘os.remove’ raising OSError for a directory argument) justify
    keeping the existing behaviour.

What you're looking for amounts to “why was ‘os.remove’ implemented as a
synonym of ‘unlink(3)’ instead of ‘remove(3)’?”.

I don't know why that behaviour was chosen, and I consider it a wart.

-- 
 \        “… no testimony can be admitted which is contrary to reason; |
  `\   reason is founded on the evidence of our senses.” —Percy Bysshe |
_o__)                        Shelley, _The Necessity of Atheism_, 1811 |
Ben Finney




More information about the Python-list mailing list