I would like to sort a file in Python based on numerical values:
My input file looks like this:
66135 - A
65117 - B
63301 - C
63793 - D
Here is a complete code for that.
with open('inputFileName') as fp:
lst = map(lambda s:s.rstrip(), fp.readlines())
with open('outputFileName', 'w') as fp:
fp.write("\n".join(sorted(lst, key=lambda s:int(s.split()[0]))))
f2.writelines(sorted(f1, key=lambda line:int(line.split()[0])))
where f2 is your output file and f1 is your input file.
you can try this way
with open('filename','r') as file:
# spilt() the line with '-'
lis=[line.strip().split('-') for line in file]
# sort the lis using the values
print sorted(lis,key=lambda x:int(x[0].strip()))