File Permissions

Fredrik Lundh fredrik at pythonware.com
Sat Mar 11 02:48:52 EST 2006


"VJ" wrote:

> I need to get the user permission of a file using python. I was trying
> the following code which i found on google grups
>
>  st = os.stat(myfile)
>     mode = st[stat.ST_MODE]
>     if mode & stat.ST_IREAD:
>         print "readable"
>     if mode & stat.ST_IWRITE:
>         print "writable"
>     if mode & stat.ST_IEXEC:
>         print "executable"
>
> I am getting a error saying
>
> " Traceback (most recent call last):
>   File "./test.py", line 23, in ?
>     if mode & stat.ST_IREAD:
> AttributeError: 'module' object has no attribute 'ST_IREAD' "
>
> any idea how to resolve this error ??

fix your spelling:

>>> help(stat)
Help on module stat:
...

    S_IREAD = 256
    S_IRGRP = 32
    S_IROTH = 4
    S_IRUSR = 256
...

> Basically i want to write into a file .If the permissions are not there
> then print a error message.
> How do i achive this ???

that's an entirely different thing: if you want open a file and have that
operation fail if the file doesn't have the right permissions, open the file
and deal with any error you get:

    try:
        f = open(filename, mode)
    except IOError, v:
        ... cannot open the file ...

or

    try:
        f = open(filename, mode)
    except IOError, v:
        import errno
        if v.errno == errno.EPERM:
            ... wrong permissions ...
        else:
            raise # some other error; propagate

(note that there's nothing that guarantees that the permissions won't
change between a stat and a subsequent open, so the "look before you
leap" approach doesn't really work for operations against the file system)

</F>






More information about the Python-list mailing list