简体   繁体   中英

Removing file permissions in python

I'm trying to remove file permissions in python. I am aware that the mode to do so is "000." However I'm seeing the removal of file permissions be done with flags as well such as "stat.S_IRWXO." Can anyone explain what I'm doing wrong

import os
import stat

file_path = 'random file'

os.chmod(file_path, stat.S_IRWXO)

My attempt with the "000" mode:

import os
import stat

file_path = "C:\Script\poop.txt"

os.chmod(file_path, 000)

EDIT

Using subprocesses, I was able to resolve the problem. I have not read the full documentation to know if chmod is not fully compatible with Windows, but it seems like it is at the very least, severely limited. Below is the code to use Window's "icacls" command to set permission. This is much more efficient.

import subprocess

file_path = r'C:\Script\poop.txt'

subprocess.check_output(['icacls.exe',file_path,'/deny','everyone:(f)'],stderr=subprocess.STDOUT)

SOURCES

calling windows' icacls from python

https://docs.python.org/2/library/os.html#os.chmod

This string:

file_path = "C:\Script\poop.txt"

is un-escaped. Thus the path becomes something like "C:Scriptpoop.txt". Use a raw string:

 file_path = r"C:\Script\poop.txt"

or use \\\\ instead of \\ .

You can try to use subprocess module as an general solution:

import subprocess

file_path = 'file.txt'
subprocess.call(['chmod', '000', file_path])

terminal output ls -la :

-r--r--r-- 1 kernel 197121     0 Mar  8 10:29 file.txt

On ms-windows, you can only use os.chmod to set and remove the read-only bit. All others bits are ignored.

Basically, file permissions work differently on ms-windows than on POSIX operating systems. You will have to modify Access Control Lists using win32 API calls. To do that from within Python, you will need pywin32 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM