0

I got a json log file that i rearrange to be correct, after this i am trying to save the results to the same file. The results are a list. but the problem that i am unable to save and will give me the following error:

write() argument must be str, not list

Here is the code it self:



import regex as re
import re


f_name = 'test1.txt'

splitter = r'"Event\d+":{(.*?)}'  # a search pattern to capture the stuff in braces

#Open the file as Read.
with open(f_name, 'r') as src:
    data = src.readlines()

# tokenize the data source...
tokens = re.findall(splitter, str(data))

#print(tokens)


# now we can operate on the tokens and split them up into key-value pairs and put them into a list
result = []
for token in tokens:
    # make an empty dictionary to hold the row elements
    line_dict = {}
    # we can split the line (token) by comma to get the key-value pairs
    pairs = token.split(',')
    for pair in pairs:
        # another regex split needed here, because the timestamps have colons too
        splitter = r'"(.*)"\s*:\s*"(.*)"'    # capture two groups of things in quotes on opposite sides of colon
        parts = re.search(splitter, pair)
        key, value = parts.group(1), parts.group(2)
        line_dict[key] = value
    # add the dictionary of line elements to the result
    result.append(line_dict)


with open(f_name, 'w') as src:
   for line in result:
     src.write(result)

i.e the code it self was not written by me -> Log file management with python (thanks AirSquid) Thanks for the assistance, New at Python here.

Tried to import json and use json.dump, also tried to append the text, but in most cases i end up with just [] or empty file.

3
  • 2
    Did you mean src.write(line) ? Commented Dec 22, 2022 at 23:25
  • Yeah, went ahead and fixed this, was getting dict error and tried to use json.dump but now its all 1 endless line and not as the screenshot, any idea to save them and still keep 1 json log line per line? Commented Dec 22, 2022 at 23:56
  • You can try src.write(json.dumps(line) + '\n') Commented Dec 23, 2022 at 0:05

0

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.