0

I am trying to get some values from txt file where lines has specific string. My text file contains more data like below,

2018-11-11 00:00:10 INFO ProtocolProcessor:417 - PUBLISH on server 80 from clientID <ClientId> on topic </data/AClientData> with QoS MOST_ONE
2018-11-11 00:00:10 INFO ProtocolProcessor:530 - Received Msg:{
"id" : "A001",
"val" : 62.0,
"ts" : "2018-11-10 23:41:21"
}
2018-11-11 00:00:10 INFO ProtocolProcessor:587 - send publish message to <tcp://35.166.43.154:80> on topic </data/BClientData>
2018-11-11 00:00:11 INFO Consumer:39 - Received a message of type PUBLISH
2018-11-11 00:00:11 INFO Consumer:58 - String received before queue:{
"id" : "B001",
"val" : 89.0,
"ts" : "2018-11-10 23:42:21"
} 

From above text I want to print Received Msg: as below format where line contains /data/AClientData

id =A001,
value = 62.0
date = 2018-11-10 23:41:21

Code Tried :

searchString = '/data/AClientData'
search = open("C:\\ReadLogUsingPython.txt","r")
for line in search.readlines():
    if searchString in line:
        #here need to take value of next line Received Msg:{ }
        #print each value
        valueDict ={"id" : "A001","val" : 62.0,"ts" : "2018-11-10 23:41:21"}
        print(valueDict['id'])
        print(valueDict['val'])
        print(valueDict['ts']) 
0

2 Answers 2

1

This is one approach using a simple iteration.

Ex:

with open(filename) as infile:
    for line in infile:
        if "/data/AClientData" in line:
            next(infile)
            extractData = [next(infile).strip().replace('"', "") for i in range(3)]
            for i in extractData:
                print("{}={}".format(*i.split(" : ")))

Output:

id=A001,
val=62.0,
ts=2018-11-10 23:41:21
Sign up to request clarification or add additional context in comments.

2 Comments

showing error print("{}={}".format(*i.split(" : "))) IndexError: tuple index out of range
What does print(i) show? or can you show extractData
1

To do something like this, I would scan character by character for the < and > fences, and then associate the content with a JSON parsed string fenced by { and }. For example

results = {}
fp = open('file.txt', 'r'):

char = fp.read(1)
nameStart, nameEnd, jStart, jEnd = None
while char:
    If char == '<'
        nameStart = fp.seek()
    elif char == '>':
        nameEnd = fp.seek()
    elif char == '{':
        jStart = fp.seek()
    elif char == '}':
        jEnd = fp.seek()
        # read the string between each start/end pair, parse json, and stash in results
    char = fp.read(1)

I typed this on a phone, so please forgive any errors. That's the rough idea though.

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.