r4b
r4b

Reputation: 49

Python3: read from a file and sort the values

I have a txt file that contains data in the following fashion:

13
56
9
32
99
74
2

each value in a different file. I created three function:

the first one is to swap the values

def swap(lst,x,y):
    temp = lst[x]
    lst[x] = lst[y]
    lst[y] = temp

and the second function is to sort the values:

def selection_sort(lst):
    for x in range(0,len(lst)-1):
        print(lst)
        swap(lst,x,findMinFrom(lst[x:])+ x)

the third function is to find the minimum value from the list:

def findMinFrom(lst):
    minIndex = -1
    for m in range(0,len(lst)):
        if minIndex == -1:
            minIndex = m
        elif lst[m] < lst[minIndex]:
            minIndex = m
    return minIndex

Now, how can I read from the file that contains the numbers and print them sorted?

Thanks in advance!


I used:

def main():
    f = []
    filename = input("Enter the file name: ")
    for line in open(filename):
        for eachElement in line:
            f += eachElement
    print(f)
    selectionSort(f)
    print(f)
main()

but still not working! any help?

Upvotes: 1

Views: 2062

Answers (2)

Monica
Monica

Reputation: 31

Good programmers don't reinvent the wheel and use sorting routines that are standard in most modern languages. You can do:

with open('input.txt') as fp:
    for line in sorted(fp):
        print(line, end='')

to print the lines sorted alphabetically (as strings). And

with open('input.txt') as fp:
    for val in sorted(map(int, fp)):
        print(val)

to sort numerically.

Upvotes: 3

Knells
Knells

Reputation: 837

To read all the lines in a file:

f = open('test.txt')
your_listname = list(f)

To sort and print

selection_sort(output_listname)
print(output_listname)

You may need to strip newline characters before sorting/printing

stripped_listname=[]
for i in your_listname:
    i = i.strip('\n')
    stripped_listname.append(i)

You probably also want to take the print statement out of your sort function so it doesn't print the list many times while sorting it.

Upvotes: 0

Related Questions