Q: Portable Way to Make Files Read Only

Christopher De Vries devries at idolstarastronomer.com
Sun Feb 13 16:20:04 EST 2005


On Sun, Feb 13, 2005 at 01:25:02PM -0600, Efrat Regev wrote:
>     I would like to recurse through a directory and make files (which match
> a specific criteria) read only. From searching the Internet, I found
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303343
>     which shows how to change file attributes to read only using the
> win32api module. That's great, but I was hoping there's a more portable way
> to do so. Is there a more portable API call to make files read only?

assuming the variable "path" is set to a string indicating the file in
question, try the following:

import os
import stat

# get the current file mode
mode = os.stat(path)[stat.ST_MODE]

# set it so it is not user, group, or other writable
os.chmod(path, mode & ~stat.S_IWUSR & ~stat.S_IWGRP & ~stat.S_IWOTH)

#or

os.chmod(path,mode & ~0222)

Chris



More information about the Python-list mailing list