0

I have a file called con.dat. I want to read the content of this file to search for a pattern. If the pattern is found, it then prints the message to the console.

con.dat

- file: /app.log
  pattern: "ERROR"
  message: "Error in App"

I get the following error: AttributeError: 'list' object has no attribute 'keys'

my test.py code is as follows:

import yaml
import re

with open("con.dat","r") as f:
    triggers = yaml.load(f)

for filename in triggers.keys():
    with open(filename,"r") as f:
        for line in f:
            trigger_info = triggers(filename)
            if re.search(trigger_info["pattern"],line):
                print("match found in line{0} for pattern{1}")
                format(line,trigger_info["pattern"])

I know my error related to triggers.keys(): but I am not sure the issue. I am new to python. Can someone guide me on how I should correct this error?

btw - my app.log file does contain a line with 'ERROR: blah blah blah' for testing

4
  • 1
    triggers.keys(): it seems that triggers is not a dictionary but a list. Lists, do not have the keys() attribute. Commented Nov 24, 2017 at 12:34
  • change line to for filename in triggers:, it should work Commented Nov 24, 2017 at 12:34
  • How do I make triggers a dictionary instead of a list? Commented Nov 24, 2017 at 12:36
  • changing line to for filename in triggers: causes a TypeError: expected str, bytes or... Commented Nov 24, 2017 at 12:43

2 Answers 2

2

Try this way, 'triggers' is a list of dictionaries:

import yaml
import re

with open("con.dat","r") as f:
    triggers = yaml.load(f)

for entry in triggers:
    with open(entry["file"], "r") as f:
        for line in f:
            if re.search(entry["pattern"], line):
                print("match found")
Sign up to request clarification or add additional context in comments.

Comments

0

triggers.keys(): it seems that triggers is not a dictionary but a list. Lists, do not have the keys() attribute.

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.