Why not check the permission of files in the "unlink" method?

The “unlink” method seems to ignore file permission. Please try the below code.

from pathlib import Path
from time import sleep
import os

txt_file = Path(__file__).parent / "tmp.txt"
with open(txt_file, "w") as f:
    print("tmp", file=f)
txt_file.chmod(0o444)

sleep(10)  # While waiting, you can confirm that the file cannot be deleted by "rm tmp.txt"

os.unlink(txt_file)  # same as txt_file.unlink(), os.remove(txt_file)

I think it would cause unintended file deletion. Is this unavoidable due to the specification in the “unlink” implementation?

Are you sure the file can’t be deleted? It deletes just fine for me. Some user-level tools will prompt, in case you didn’t want that, but a read-only file is not a problem for unlinking.

It’s different if the directory is read-only.

2 Likes

Thank you for the reply.
I realized that I couldn’t delete a file iff the directory is read-only.

Note that on Windows, os.chmod() behaves like the C runtime _chmod() function, which uses the readonly file attribute as the basis for write permission. For example, chmod(0o444) sets the readonly file attribute. The presence of this attribute causes opens that request write access to a data stream (see file streams) to fail with a permission error. It doesn’t prevent modifying file metadata or prevent writing to an index stream in a directory (i.e. the linked entries in a directory). It also doesn’t prevent getting delete access to a file, directory, or named data stream, so renaming a readonly file is allowed. However, requesting to actually delete a readonly file, directory, or data stream fails with a permission error (actually STATUS_CANNOT_DELETE, which gets mapped to a permission error at a higher level).

According to this model, unlinking a file requires having ‘write’ access to the file and has nothing to do with having ‘write’ access to the parent directory. This would be conceptually wrong in POSIX. It also doesn’t take into account the actual permissions on filesystems that support security.

Perhaps, but the OP mentioned testing the readonliness with the rm command, not “go to the folder and delete the file” which is how a typical Windows user would say it.

I was just clarifying a horrible situation on Windows in this regard, for all readers, not for the original poster. The os.chmod() function and os.stat().st_mode permissions shouldn’t be implemented at all on Windows.

1 Like

Fair enough. Windows file systems and the Windows kernel have a number of fundamental differences, and honestly, anyone who’s writing code that works on multiple platforms and manipulates FS permissions is going to HAVE to be aware of those differences. Same if you do anything with signals.