[Tutor] [HELP]how to test properties of a file

Alan Gauld alan.gauld at freenet.co.uk
Mon Apr 4 23:43:37 CEST 2005


> The simplest, IMHO, is :
>
> try:
>    f = file(filename, "w")
>    [...]
> except IOError:
>    print "The file is not writable"
>
> Of course, not that this method empty the file if it is writable !
The
> best is to just put your IO code in such a try block ... That way,
> you're sure the file has the right mode.

Its not really the simplest, its not efficient and it might be
dangerous
if the file is not empty. At the very least open using 'a' to avoid
obliterating the file!!

However the os.stat function and stat module do what you want safely
and more comprehensively:

-----------------------------------
Help on module stat:

NAME
    stat - Constants/functions for interpreting results of
    os.stat() and os.lstat().

FILE
    /usr/lib/python2.3/stat.py

DESCRIPTION
    Suggested usage: from stat import *

DATA
    ST_ATIME = 7
    ST_CTIME = 9
    ST_DEV = 2
    ST_GID = 5
    ST_INO = 1
    ST_MODE = 0
    ST_MTIME = 8
    ST_NLINK = 3
    ST_SIZE = 6
    ST_UID = 4
    S_ENFMT = 1024

-----------------------------------------

The constants above are the indices into the tuple returned by
os.stat()
That will tell you most of the things you need to know,
check the docs to find out what they all mean.
For your purposes the important one is ST_MODE.

So

import os
from stat import *
status = os.stat('somefile.txt')[ST_MODE]
if status & S_IWRITE: print 'writable'
elif staus &  S_IREAD: print 'readable'
else: print 'status is ', status

Notice you have to use bitwise AND (&) to extract the status bits.

HTH

Alan G.



More information about the Tutor mailing list