[Discuss] File permissions in Python

Deryk Barker dbarker at camosun.bc.ca
Sat Aug 5 11:35:12 PDT 2006


Deryk Barker wrote:

> Adam Parkin wrote:
>
>> Continuing in the questions for the Python gurus series of 
>> e-mails.... =8-p
>>
>> I've been banging my head for a little bit trying to figure out a 
>> quick and easy way to read a file's permissions inside of a Python 
>> script. What I want to do is be able to tell the rwx permissions 
>> (ideally for all groups).  I have found the os.stat function, and 
>> it's ST_MODE field, but this returns a decimal number for all 
>> permissions (not just rwx for the three groups).  I suppose I could 
>> figure out the permissions from the number via some and'ing and 
>> or'ing, but is there not some easier way?
>>
>> If it helps: what I'm working on is taking all of the exercise 
>> solutions to the problems in the Learning Perl book and rewriting 
>> them in Python to help learn the langauge.  The chunk of code I'm 
>> stuck on right now is this (in Perl):
>>
>>     $x = "foobar.txt"
>>     print "$x is: ", ((-R $x) ? "readable " : ""),
>>         ((-W $x) ? "writeable " : ""),
>>         ((-x $x) ? "executable\n" : "\n");
>
>
> The exact equivalent of what you're doing here would seem to be the 
> os.access function.
>
> name = 'foobar.txt'
> print name, 'is',
> if os.access (name, os.R_OK):
>    print 'readable',
> if os.access (name, os.W_OK):
>    print 'writeable',
> if os.access (name, os.X_OK):
>    print 'executable',
> print
>
Of course, if you have no permission at all the output will simply be:

    foobar.txt is

but that unless I'm mistaken (I know my perl is rusty)  is precisely 
what your perl code does.

Only trying to emulate...:-)



More information about the Discuss mailing list