1

if the data in the text file has is less than 10 (for example 4,2,3,1) it will sort the data accordingly. However, if the data is more than 10 (for example (3,199,4,5), it will sort to 199,3,4,5 instead of ascending order. Please help

def readFile():
        try:
            fileName = open("haha.txt",'r')
            data = fileName.read().split()
            data.sort() 
            print(data)

        except IOError:
                    print("Error: File do not exist")
                    return
Aurora_Titanium
  • 472
  • 1
  • 8
  • 23
  • 1
    Wow! You've discovered a completely obvious bug in a widely used piece of software!! Or...maybe not. The problem, as others have said, is that you're sorting character strings, and `sort` may not behave as you expected. As a general rule you might want to consider that whenever you think you've found that really obvious bug in a widely used piece of software, it may be that you're mistaken in your understanding of the software. In 40+ years of software development I've found very, very few actual bugs. I have, however, found many, many failures in my understanding. YMMV. Best of luck. – Bob Jarvis - Слава Україні Dec 29 '15 at 01:34

2 Answers2

8

You are sorting strings lexographically, and the 1 character has a lower value than the 3 character. Adding ,key=int to the sort function would fix this.

data.sort(key=int)
pppery
  • 3,731
  • 22
  • 33
  • 46
1

Because items in data are strings, you can turn the item into ints by:

data = [int(item) for item in data]
pppery
  • 3,731
  • 22
  • 33
  • 46
Dazhuang
  • 56
  • 3