0

I'm trying to get a value from a variable inside some files, here is the code:

path = '/opt/log/...'
word = 'somevariable'

def enumeratepaths(path=path):
    paths = []
    for dirpath, dirnames, files in os.walk(path):
        for file in files:
            fullpath = os.path.join(dirpath, file)
            paths.append(fullpath)
    return paths

def read_files(file):
    try:
        file_open = open(file, 'r')
        search = file_open.read()
        find = search.find(word)
        find_start = find + 7
        find_stop = find + 9
        result = int(search[find_start:find_stop])
        return int(result)
    finally:
        file_open.close()

def main():
    for files in enumeratepaths():
        read_files(files)

if __name__ == "__main__":
    main()

The problem is that some files don't have the variable inside, because some error occurred. IN this case, this script returns an error:

    result = int(search[find_start:find_stop])
ValueError: invalid literal for int(): RE

I want to get these values as int, but I'm stuck.

And another question: If the file does not have that search value, how can it be that it returns things like "RE"?

1
  • 1
    do you have a sample of the file that is outputting the error? Commented Mar 21, 2011 at 18:39

2 Answers 2

3

If find can't find the string you are searching for, it will return -1. So you can check the return value of search.find(word) to see if word was actually found.

At the moment you just proceed even if the searched word as not found. find_start will end up as 6, find_end as 8, and probably search[6:8] contains the characters "RE", which leads to the error message you see.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, you're right, i just proceed anyway, and got that RE'
2

You could solve it like this:

try:
    int(somestring)
except (ValueError, TypeError):
    pass # not an int... what do you want to do now?

Or if you're always checking a string that should be digit only:

if somestring.isdigit():

2 Comments

Please switch the order. The cleaner solution should be first.
@S.Lott: fair enough, I've changed it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.