2

I'm trying to do, check if line in a config file contains a string ('string1') or not, and if so then print the string and a found message ('Found string1'). I need to store the found message as a variable.

The problem is exactly here (I don't have any results for print(line) and for print('Found string1'):

def get_version():
    logger.info('Started')
    for file in os.listdir(running_config_dir):
        if file.endswith('.config'):
            for line in file:
                if str('string1') in line:
                    print(line)
                    print('Found string1')
        else:
            logger.critical('Running Configuration not found')

    logger.info('Finished')

Here is my config file,

string1
string2
string3

1 Answer 1

3

file is a string, containing a filename. As such, iterating over the string gives you individual characters, not the contents of the file:

>>> file = 'foo'
>>> for line in file:
...     print(line)
... 
f
o
o

You need to open the filename to get a file object:

with open(file) as fileobj:
    for line in fileobj:

Note that the '...' literal string syntax already produces a string object, there is no need to pass that to a str() call.

I'm not sure by what you mean with storing the found message as a variable; you already have access to the line variable, so you could just return that:

def get_version():
    logger.info('Started')
    version = None
    for file in os.listdir(running_config_dir):
        if file.endswith('.config'):
            with open(file) as fileobj:
                for line in fileobj:
                    if 'string1' in line:
                        print(line)
                        print('Found string1')
                        version = line.strip()
        else:
            logger.critical('Running Configuration not found')

    logger.info('Finished')
    return version
Sign up to request clarification or add additional context in comments.

Comments

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.