Windows 11 Python and Windows File System Permissions

Josephur

Windows Forum Admin
Staff member
Premium Supporter
Microsoft Certified Professional
Joined
Aug 3, 2010
Location
Indiana, USA
What is the best way to read a files owner and permissions, create a new file then apply those permissions without using the subprocess method or command line icacls etc.
 
The best way to handle file permissions and ownership is to use the built-in Python libraries like `os` and `shutil`.

In order to read file permissions and ownership, you should use the following code:

```python
import os
import stat

file_path = 'yourfile.txt'

# get file permissions
file_info = os.stat(file_path)
file_permissions = stat.S_IMODE(file_info.st_mode)

# get owner id
owner_id = file_info.st_uid
```
In the above code, `st_mode` contains information about file permissions, which you get using `stat.S_IMODE`. `st_uid` attribute is for user id who owns the file.

To create a new file via Python, you can use the `open()` function:

```python
new_file_path = 'new_file.txt'

# create a new file
open(new_file_path, 'a').close()
```

To apply the read permissions to a newly created file, you can use the `os.chmod()` method and ownership by `os.chown()` method:

```python
# applying permissions
os.chmod(new_file_path, file_permissions)

# applying onwership
os.chown(new_file_path, owner_id, -1)
```
The above code applies the same permissions as the original file to the new file. Note that you need superuser privileges to change the owner of the file.

Please be aware that managing file permissions and ownership is a sensitive task and always make sure to verify your actions to avoid security issues.

Remember that this code sample will work fine on Unix-based systems like Linux and macOS. However, on Windows, Python's `os.chmod` doesn't support all permissions and `os.chown` function is not available in Python for Windows. In case you are working on Windows, you have to approach it differently, perhaps by using libraries that support Windows ACLs, like pywin32 or win32security as working with file permissions on Windows is more complicated due to the Access Control Lists (ACLs).
 
I get an error,
Traceback (most recent call last):
File "C:\Temp\test.py", line 27, in <module>
os.chown(new_file_path, owner_id, -1)
^^^^^^^^
AttributeError: module 'os' has no attribute 'chown'
 
Back
Top Bottom