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
Since you're reading data from
file
, we have every line as a string. So, you need to usesplit
method in combinationint
constructor.This can be achieved using a list comprehension.
line.split(':')[1]
gives as the string2,1,4,3,6,5
Another
split
by comma separator gives us the list ofnumbers
. I usedint
constructor because aftersplit
method we have them likestrings
.