How to sort numbers from text file after splitting

369 Views Asked by At

Could someone please help me with sorting numbers from a text file once split. I have the following text file which i need to sort the numbers from low to high. No matter the sequence or number values I need to sort them from low to high.

So far I have the following code but its still not sorting the numbers. Any help would really be great. Thank you.

Text file (input.txt):

min:2,1,4,3,6,5

max:1,2,3,4,5,6

avg:1,2,3,4,5,6

My code so far:

inputFile = open("input.txt", 'r')
lineList = inputFile.readlines()
print (lineList)
for line in lineList:
    numbers = [int(item) for item in line.split(':')[1].split(',')]
    numbers.sort()
    with open('inputcopy.txt', 'a') as f:
        for line in lineList:
            numbers.sort()
            f.write(line)     
2

There are 2 best solutions below

0
On BEST ANSWER

Try this :

inputFile = open("input.txt", 'r')
lineList = inputFile.readlines()
print (lineList)

fileHandle = open('inputcopy.txt', 'a')
for line in lineList:
    numbers = [int(item) for item in line.split(':')[1].split(',')]
    numbers.sort()
    fileHandle.write("%s\n" % numbers)  
fileHandle.close()
0
On

To clean it up a bit

for line in lineList:
    # Split your line into your label and number list
    label, numbers = line.strip().split(':')
    # Convert the numbers into integers and sort them
    numbers = [int(item) for item in numbers.split(',')]
    numbers.sort()
    # Convert the numbers back into a comma-delimited string
    numbers = ','.join(map(str, numbers))
    with open('inputcopy.txt', 'a') as f:
        # Write your data back out
        f.write('%s:%s\n'.format(label, numbers))