[Tutor] permissions reading of a file

Kristoffer Erlandsson krier115@student.liu.se
Fri May 16 04:03:02 2003


On Sat, May 17, 2003 at 07:41:57PM +1200, Thomas CLive Richards wrote:
> > The modes you can test for is R_OK (is the file readible?), W_OK
> > (writable?), X_OK (executable?) and F_OK (does the file exist?). You
> > just combine these using inclusive or (|).
> 
> umm... surely '|' is an "or"???
> 
> shouldn't it be an "and"?? It's && in C, what is it in python??
> 

It should be an or. As in c the operators | and & perform bitwise or and
bitwise and, respectively. That is, they compare the bits of two
integers two by two using or or and. The way things work in for example
os.access now is that os.R_OK = 4 = 0100b, os.W_OK = 2 = 0010b, os.X_OK
= 1 = 0001b. So each of these number have one bit each set. What will
happen when we perform a bitwise or on two of them?

>>> os.R_OK|os.W_OK
6

Which is the same as 0110b. So what python now did was to compare the
bits in the number 4 and the number 2, two by two. This teqnique is
often used when handling "flags" where you have an integer and it means
different things depending on what bits are set.

>>> os.R_OK|os.W_OK|os.X_OK
7

Which is the same as 0111b.

These bitwise operators are very different from the logic ones (&& and ||
in c, 'and' and 'or' in python). The logic ones just compare the two
operands and return true or false (or some values that are true or
false), wheras the bitwise operators perform what I showed above and
return a new integer.

Hope it makes things clearer. I tried at least ;)

Regards,
Kristoffer

-- 
Kristoffer Erlandsson
E-mail:  krier115@student.liu.se
ICQ#:    378225