File Sorting In Python
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 Output should be: 63301 - C 63793 - D 65117
Solution 1:
f2.writelines(sorted(f1, key=lambda line:int(line.split()[0])))
where f2 is your output file and f1 is your input file.
Solution 2:
you can try this way
withopen('filename','r') as file:
# spilt() the line with '-'
lis=[line.strip().split('-') for line in file]
# sort the lis using the valuesprintsorted(lis,key=lambda x:int(x[0].strip()))
Post a Comment for "File Sorting In Python"