Redicebergz
Redicebergz

Reputation: 37

Sorting Numbers Embedded within a String List

I have a data text document that looks like this:

(data.txt)

John|5|02-20-2019
Sally|3|02-19-2019
Billy|12|02-12-2019
Smith|1|02-16-2019

I want to be able to sort these values into a new text document called (data_sorted.txt) based on the number that is embedded within the '|'. So basically I would want the output document to be:

Billy|12|02-12-2019
John|5|02-20-2019
Sally|3|02-19-2019
Smith|1|02-16-2019

Any ideas? I have tried making this into a list with split('\n') but I'm not sure what I can do after that. I know how to isolate the numbers and then I could compare the numbers alone, but I don't know how I would keep their identifying other information. Thanks!

Upvotes: 1

Views: 61

Answers (1)

Shay
Shay

Reputation: 38

with open('data.txt', 'r') as infile:
    datalist = list(infile)

datalist = sorted(datalist, key=lambda x: int(x.split('|')[1]), reverse=True)

with open('sorted_data.txt', 'w') as outfile:
    for line in datalist:
        outfile.write(line)

Upvotes: 1

Related Questions