0

I'm trying to figure out a simple way to sort numbers in ascending order from a file using python.

This is what I have got so far - but it doesnt seem to work!

input_file = open('C:\\Users|\Desktop\\data.txt') 
for line in input_file:
    print line

print('Before: ', input_file)
insertion_sort(input_file)
print('After : ', input_file)
def insertion_sort(items):
    """ Implementation of insertion sort """
    for i in range(1, len(items)):
        j = i
        while j > 0 and items[j] < items[j-1]:
            items[j], items[j-1] = items[j-1], items[j]
            j -= 1

Any help would be greatly appreciated!!

Fredd444
  • 37
  • 4

1 Answers1

0

You just have some grammatical errors:

  • you should declare the insertion_sort function before use it
  • you can't print a File type, you should make a List to read the file content, then sort the List, return the List and print the List
  • your file name maybe wrong, use / is better in Windows

Try this:

input_file = open('C:/Users/Desktop/data.txt')

lst = []
for line in input_file:
    lst.append(int(line.strip()))

def insertion_sort(items):
    """ Implementation of insertion sort """
    for i in range(1, len(items)):
        j = i
        while j > 0 and items[j] < items[j - 1]:
            items[j], items[j - 1] = items[j - 1], items[j]
            j -= 1
    return items

print('Before: ', lst)
print('After : ', insertion_sort(lst))
zhangnew
  • 11
  • 1
  • 1
  • 6
  • Welcome to Stackoverflow! When giving an answer it is preferable to give [some explanation as to WHY your answer](http://stackoverflow.com/help/how-to-answer) is the one. Code only answer can end up getting deleted. – Stephen Rauch Feb 15 '17 at 03:54