2

I'm writing a Python script. I need to return line that contain largest 'uid' field from a text file. For example, in the below text file example:

{
    "uid": 683,
    "user_id": "2",
    "timestamp": datetime.datetime(2020, 5, 17, 16, 39, 54),
    "status": 1,
    "punch": 0,
}, {
    "uid": 684,
    "user_id": "4",
    "timestamp": datetime.datetime(2020, 5, 17, 16, 41, 20),
    "status": 1,
    "punch": 0,
}

Return Text File ex:

{
    "uid": 684,
    "user_id": "4",
    "timestamp": datetime.datetime(2020, 5, 17, 16, 41, 20),
    "status": 1,
    "punch": 0,
}
Abdullah Md
  • 151
  • 15

3 Answers3

3

Here is my solution, instead of reading a text file I used a text from string variable text.

Final result (entry with maximal uid) is contained inside max_entry variable. This result I write as string into text file result.txt.

Try it online!

import datetime

text = """
{
    "uid": 683,
    "user_id": "2",
    "timestamp": datetime.datetime(2020, 5, 17, 16, 39, 54),
    "status": 1,
    "punch": 0,
}, {
    "uid": 684,
    "user_id": "4",
    "timestamp": datetime.datetime(2020, 5, 17, 16, 41, 20),
    "status": 1,
    "punch": 0,
}
"""

data = eval('[' + text + ']')
max_entry = max(data, key = lambda e: e['uid'])
print(max_entry)

with open('result.txt', 'w', encoding = 'utf-8') as f:
    f.write(str(max_entry))

Output:

{'uid': 684, 'user_id': '4', 'timestamp': datetime.datetime(2020, 5, 17, 16, 41, 20), 'status': 1, 'punch': 0}
Arty
  • 14,883
  • 6
  • 36
  • 69
1

You show that your "text-file" is a list of dictionaries. So you could do something like:

import datetime

text_file = {
    "uid": 683,
    "user_id": "2",
    "timestamp": datetime.datetime(2020, 5, 17, 16, 39, 54),
    "status": 1,
    "punch": 0,
}, {
    "uid": 684,
    "user_id": "4",
    "timestamp": datetime.datetime(2020, 5, 17, 16, 41, 20),
    "status": 1,
    "punch": 0,
}

def return_highest_ui_line(text_file):
    temp = []
    for i,sub_dict in enumerate(text_file):
        temp.append([sub_dict['uid'],i])
    return text_file[sorted(temp)[-1][1]]


return_highest_ui_line(text_file)

output:
{'uid': 684,
 'user_id': '4',
 'timestamp': datetime.datetime(2020, 5, 17, 16, 41, 20),
 'status': 1,
 'punch': 0}

     
KaPy3141
  • 161
  • 14
0

I solved this by:

import datetime
with open('C:/Users/UI UX/Desktop/newss.txt') as infile:
    for line in infile:
        data = eval('[' + line + ']')
        max_entry = max(data, key=lambda e: e['uid'])
        print(max_entry)

        with open('result.txt', 'w', encoding='utf-8') as f:
            f.write(str(max_entry))
Abdullah Md
  • 151
  • 15