How to sort numbers and write to new text file

611 Views Asked by At

could anyone please help me with the following problem. I have a task where I need to sort numbers from a txt file from lowest to highest value. No matter the combination of the numbers or length of text it needs to sort the numbers from lowest to highest. Any help will really be appreciated.

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

I have written some code as follows but its just arranging the line title alphabeticaly

inputFile = open("input.txt", 'r')
lineList = inputFile.readlines()
lineList.sort()
print (lineList)
for line in lineList:
    print(line)
    with open('inputcopy.txt', 'a') as f:
        for line in lineList:
            lineList.sort()
            f.write(line)

Thank you for any help

2

There are 2 best solutions below

0
On

Since you're reading data from file, we have every line as a string. So, you need to use split method in combination int constructor.

This can be achieved using a list comprehension.

for line in lineList:
    numbers = [int(item) for item in line.split(':')[1].split(',')]

line.split(':')[1] gives as the string 2,1,4,3,6,5

Another split by comma separator gives us the list of numbers. I used int constructor because after split method we have them like strings.

0
On

You could use regex. Note that you need to either convert to int or use a custom function that considers the integer representation

for line in lineList:
   sorted_line = sorted(map(int, re.findall(r'\d+',line)))


for line in lineList:
   sorted_line = sorted(re.findall(r'\d+',line), key=lambda x:int(x))