Home > Software engineering >  Sort value in txt file contain {string, number} using Python
Sort value in txt file contain {string, number} using Python

Time:10-12

I have a .txt file as per below:

testa, 10
testb, 50
testc, 20

I want to sort it reversely, based on the number each line located on the right side of comma, become the result like below:

testb, 50
testc, 20
testa, 10

I have tried to append each line to a list and use sort(), but fail. Any way to do that in Python? Take note my file is txt.

CodePudding user response:

You can specify a key=func argument to the sorted() built-in function, which specify a value to be used as comparing value between items. The code to do it would be:

lines = open('input.txt').read().splitlines()
splitted = (line.split(', ') for line in lines)
items = ((i[0], int(i[1])) for i in splitted)

# Reversed sort
reversed_items = sorted(items, key=lambda i: -i[1])

open('output.txt', 'w ').write('\n'.join((f"{i[0]}, {i[1]}" for i in reversed_items)))

Documentation: https://docs.python.org/3/howto/sorting.html#key-functions

CodePudding user response:

This prints the lines in reverse order

with open('test.txt') as f:
    lines = f.readlines()
 
with open('out.txt', 'w') as f:
    for line in sorted(lines, key=lambda x: x.split()[1], reverse=True):
        f.write(line.strip()   '\n')

Edited to write the out.txt file

  • Related