I am trying to read a file as follows and I want to log an error if the file does not exist. So I wrote the following code. But this code does not go into the except block at all. I don't have the file for sure.

    DEFAULT_ROLE_PROPERTIES = '/tmp/role.properties'

        self.role_properties = os.environ.get('VAULT_ROLE_PROPERTIES', DEFAULT_ROLE_PROPERTIES)
        with open(self.role_properties, 'r') as rolefp:
        self.role_id = cfg.get('region', 'role_id')
    except Exception as msg:
        self.log.error("Unable to read role properties")

I am not sure what is wrong with the syntax here. The above code is in an init function (constructor) could that be the issue?

ls /tmp/role.properties
ls: cannot access /tmp/role.properties: No such file or directory

1 Answers

Rachel Gallen On

You could use os.path to check that the path exists (first) before proceeding with getting environment/other attributes

Sample code:

import os.path

If you were checking to see if a particular file was present, and valid (not empty) you could use os.stat

    if os.stat(filename).st_size > 0:
       print "file present"
       print "file present but empty"
except OSError:
    print "No file"

Hope this helps