1

Hi I'm looking for help with sorting my text file in numerical order, I have found How to sort a text file numerically? which shows me how to sort the numbers but in my text file I have the numbers in with other non numeric characters.

My text file might look like this:

Username1, 78 pts
Username2, 64 pts
Username3, 98 pts
Username4, 81 pts
Username5, 43 pts
Username6, 56 pts

The usernames would be different those are just placeholders

I have tried sorting with the numbers at the front of each line but since the answer linked above converts the entire line into integers I only get greeted with an error. If anyone knows how to sort all the whole line using just those numbers that would be greatly appreciated. Thanks, Joe

Joliver
  • 17
  • 3

2 Answers2

1

Here you go:

#!/usr/bin/env python3

with open('./test.txt', 'r') as fh:
  lines = [l.rstrip() for l in fh.readlines()]

lines = [x.split() for x in lines]
lines.sort(key=lambda x: x[1])
lines = [' '.join(x) for x in lines]

with open('./test.txt', 'w') as fh:
  fh.write('\n'.join(lines))

Sorted file:

Username5, 43 pts
Username6, 56 pts
Username2, 64 pts
Username1, 78 pts
Username4, 81 pts
Username3, 98 pts
777moneymaker
  • 697
  • 4
  • 15
1

The following should work, with the gived structure of your lines:

with open('so.txt') as f:
    l=f.readlines()

l[-1]=l[-1]+'\n'

with open('so.txt', 'w') as f:
    for i in sorted(l, key=lambda x: x[x.find(' ')+1:x.find('pts')]):
        f.write(i)

Output:

Username5, 43 pts
Username6, 56 pts
Username2, 64 pts
Username1, 78 pts
Username4, 81 pts
Username3, 98 pts
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30