-1

highscore.txt

16
23
17
15
60
40
13

Here's what I have

Top_Score = open("highscore.txt", "r+")
for line in Top_Score.readlines():
    print(line)

Top_Score.close()

Preferably prints only the top 5 smallest numbers. Any help would be appreciated.

Sample Output

13
15
16
17
23
40
60
Yeah Bruh
  • 33
  • 1
  • 7
  • 2
    Can you please edit your question to show what you have tried to tackle the problem? There is no sorting going on anywhere in that code. Are all numbers of the same digit count? What sort order do you want for ``2, 12, 1``? – MisterMiyagi Aug 06 '20 at 06:49

4 Answers4

3

You just need to store the input numbers in a python list and then sort it.

Top_Score = open("a.txt", "r+")
X = []
for line in Top_Score.readlines():
    X.append(int(line))    
X.sort()
for i in range(5):
    print(X[i])
Top_Score.close()
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Anuneet Anand
  • 331
  • 1
  • 9
2
In [85]: data = sorted(map(int, open("highscore.txt")))

In [86]: data
Out[86]: [13, 15, 16, 17, 23, 40, 60]
bigbounty
  • 16,526
  • 5
  • 37
  • 65
  • 2
    Note that there is no need for the intermediate list – ``sorted`` already creates one. A generator work as well. ``int`` also ignores leading/trealing whitespace, so the ``.strip`` is superfluous as well. ``sorted(map(int, open("highscore.txt"))`` should work, using much less memory. – MisterMiyagi Aug 06 '20 at 06:50
1

This will print out the 5 smallest numbers

f = open("highscore.txt", "r+")
numbers = sorted(list(map(int, f.readlines())))
print(numbers[:5])
Marko Borković
  • 1,884
  • 1
  • 7
  • 22
-1

You can add it to a List

numbers = []
with open File blablabla:
    for line in File:
          numbers.append(line)
result = sorted(numbers)

The sorted() function sort the Items of the List. After that you can clear your File, and write the sorted Items of the result to file for Example.

BPP-DEV
  • 21
  • 6
  • This will not correctly sort numbers of different digit count. Compare ``sorted(['1', '2', '12'])``. – MisterMiyagi Aug 06 '20 at 06:47
  • It works? So I've tryed in Python Sandbox and IT works? Or what did you mean? – BPP-DEV Aug 06 '20 at 07:02
  • It works for the sample input, since these just happen to be ones where lexicographic sort equals numeric sort. It will fail for most other inputs. – MisterMiyagi Aug 06 '20 at 07:04
  • You mean If the File has one line with a String ect? Yes then it doesn works. But you can Convert the readet "numerical" lines with int(line). – BPP-DEV Aug 06 '20 at 07:08