newbie os.stat question

Ben Hutchings do-not-spam-ben.hutchings at businesswebsoftware.com
Thu Apr 3 14:13:33 EST 2003


In article <AV_ia.7382$4P1.570905 at newsread2.prod.itd.earthlink.net>,
Tipton Bandy wrote:
> 
> I've got my first python utility working pretty good, but
> I just need help on one point.
> 
> I need to test a filename and return true or false based on 
> whether the file is readable and writable by the user running
> my utility. Oh, yes, this is on Linux:)
> I'm used to writing things like, 'if [ -w $filename ]' in bash.
> 
> I think I should use os.stat() somehow, but it seems like a lot
> of code would be required to check the appropriate field (user,
> group, or others) based on the ownership of the file and the
> uid of the user.
> 
> This seems like such a common thing.  Is there a pre-written function
> to handle it?

os.access

(But this is fairly useless, because the situation could change by
the time you actually try to use the file.  You should just attempt
to use the file and catch OSError exceptions:

    try:
        f = open(filename)
    except OSError, e:
        if e.errno == errno.EPERM:
           print 'Operation is not permitted'

)




More information about the Python-list mailing list