When will os.remove fail?

Alain Ketterlin alain at universite-de-strasbourg.fr.invalid
Sun Mar 12 14:45:54 EDT 2017

Steve D'Aprano <steve+python at pearwood.info> writes:

> On Linux, if I call os.remove on a file which I own but don't have write
> permission on, the file is still deleted:
> py> f = open('/tmp/no-write', 'w')
> py> os.path.exists('/tmp/no-write')
> True
> py> os.chmod('/tmp/no-write', 0)  # Forbid ALL access.
> py> os.remove('/tmp/no-write')
> py> os.path.exists('/tmp/no-write')
> False
> It seems that os.remove on Linux will force the delete even if the file is
> read-only or unreadable, provided you own the file.

Your permissions on the file do not really matters. It's all about your
permissions on the parent directory (removing a file is really modifying
the parent dir). Actually, it is even slightly more complicated. Here is
an excerpt of the unlink(2) call (which does the job) listing common
error cases:

| EACCES Write access to the directory containing pathname is not allowed
|        for  the  process's  effective UID, or one of the directories in
|        pathname did not allow search permission.  (See also  path_reso‐
|        lution(7).)
| ELOOP  Too  many  symbolic  links were encountered in translating path‐
|        name.
| EPERM (Linux only)
|        The filesystem does not allow unlinking of files.
|        The  directory  containing pathname has the sticky bit (S_ISVTX)
|        set and the process's effective UID is neither the  UID  of  the
|        file  to be deleted nor that of the directory containing it, and
|        the  process  is  not  privileged  (Linux:  does  not  have  the
|        CAP_FOWNER capability).
| EROFS  pathname refers to a file on a read-only filesystem.

> Does os.remove work like this under Windows too?

No, Windows has its own set of rules:


> Under what circumstances will os.remove fail to remove a file?
> If you don't own the file and have no write permission, if it is on
> read-only media, anything else?

I'm not sure which system you are asking about, here. See above.

-- Alain.

More information about the Python-list mailing list