I have a text file(data.txt) containing names and scores 1:1 i.e.:
Mike = 1\n John = 2\n Cam = 3\n
I want to sort the integers along with the corresponding name in ascending and descending order.
with open(filepath, 'r') as file:
list = []
for line in file:
list.append(line[1:-1].split(","))
list.sort(key=lambda x: int(x[4]))
Yes, i have done some research however it doesn't work, i was hoping one of you guys could help me fix the code above. I know i must convert the data within the text file into a list then sort the list then put write back to the text file, but i am not sure how.
Source: How do i sort a text file numerically highest to lowest?
解决方案
Here's an example, doing it in memory using the sorted() function.
with open(filepath, 'r') as file:
sorted_data=sorted(file.readlines(),
key=lambda item: int(item.rsplit('=',1)[-1].strip()))
sorted_data will then contain a list of the sorted rows.
Here it is:
open the file:
with open(filepath, 'r') as file:
Get all the lines of the file (as a list):
file.readlines()
For each line in the file, sorted() will numerically sort them based on the output of passing each line into the "key" function.
The "key" function takes a line, splits it by the "=" symbol, then takes the last part of that (the part after the = sign), strips any leading or trailing whitespace (.strip()) and returns the value cast to an integer (int) .
Sorted takes the lines and orders them using the numbers output by the key function.