Why doesn't os.remove work on directories?

eryk sun eryksun at gmail.com
Wed Dec 23 03:50:56 EST 2015


On Tue, Dec 22, 2015 at 10:29 PM, Random832 <random832 at fastmail.com> wrote:
>
> 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?

Guido added os.remove as a synonym for os.unlink in version 1.4 (1996)
[1]. This is also mentioned in the NEWS for 1.4b1 [2].

Note that C99 only specifies the behavior for files, as opposed to the
extended unlink/rmdir that POSIX mandates [3].

    7.19.4.1 The remove function
    Synopsis
    1
    #include <stdio.h>
    int remove(const char *filename);
    Description
    2
    The remove function causes the file whose name is the string
    pointed to by filename to be no longer accessible by that
    name. A subsequent attempt to open that file using that name
    will fail, unless it is created anew. If the file is open,
    the behavior of the remove function is implementation-
    defined.
    Returns
    3
    The remove function returns zero if the operation succeeds,
    nonzero if it fails.

For Windows, the CRTs remove() function doesn't implement the extended
POSIX behavior. It only calls DeleteFile, not RemoveDirectory. (In
contrast the native NtDeleteFile [4] works for both files and
directories, and relative to an open handle like unlinkat.)

[1]: https://hg.python.org/cpython/rev/9fa2228bb096
[2]: https://hg.python.org/cpython/file/v1.4/Misc/NEWS#l565
[3]: http://pubs.opengroup.org/onlinepubs/9699919799/functions/remove.html
[4]: https://msdn.microsoft.com/en-us/library/ff566435



More information about the Python-list mailing list