Change file ownership
When desired and permitted by the computer filesystem, it’s possible to change file ownership. This may be necessary when a file was inadvertently created with root / admin ownership by mistake, and it’s necessary for a general user to edit or access the file. Changing file ownership can have unexpected consequences, like removing the ability of others to access the file or run a program depending on the file. Therefore, file ownership changes should be done only when necessary and with consideration for others who may depend on the file.
These examples assume the file “my.txt” is in the current directory and the user logged in should own the file. These tasks are similarly done in other languages such as Go or Julia.
As long as the user has filesystem permission, Python can easily change file ownership across operating systems.
import shutil
import getpass
shutil.chown("my.txt", user=getpass.getuser())
On Windows check ownership of the file by Command Prompt:
dir /q my.txt
or PowerShell:
(get-acl my.txt).owner
Windows uses the takeown command to change file ownership. For simplicity we assume the desired user is logged in and executing the command.
takeown /f my.txt
On macOS / Linux check ownership of the file by
ls -l my.txt
For simplicity we assume the desired user is logged in and executing the command chown:
chown $whoami:$whoami my.txt