A portable way to determine if a process can move / delete a file?

What would be a portable way to determine if a Python process can move / delete a file without to move / delete the specified file?

Use case: I would like to inform the user about the script whether the move / delete operations will be successful or unsuccessful before the start of processing.

If there is a solution that only works on Linux, everything will be okay for now.

Thanks.

update: I understand that os.access can be used, but is limited to the real uid / gid.

+7
source share
2 answers

Would open a file to add work?

try: open(filename,'a').close() 

... and catch any exception indicating that this failed?

Use with caution, I'm really not sure that I will not do anything wrong by mistake. For example, at least temporarily, you will lock the file, and I do not know what this will do with the binary.

+1
source

If I remember correctly, there are three conditions for UNIX:

  • The user can write to the directory containing the source file (to delete or move)
  • If the directory containing the source file has the sticky bit set, the source file must belong to the user (to delete or move).
  • In the case of moving, in addition, the user can write to the directory where he should be moved to

In python, conditions 1 and 3 can be checked with os.access and condition 2 with os.stat here and here .

update:. If you want to work with an efficient UID, use os.geteuid() and interpret the stat results to check for 1 and 3 as well.

0
source

All Articles