Python Forum

Full Version: Split and sort input file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there, I need help with the following code. I am trying to sort the list but only getting the last sentence of the file sorted. What am I doing wrong?
fname = input("Enter file name: ")
fh = open(fname)
lst = list(fh)
for line in lst:
    line = line.rstrip()
    print line
    y = line.split()

k = y.sort()
print y
lines 9 and 10 are not part of the for loop, so the sort is only being performed on the final line. Indent them properly and it will work.
Thanks TomToad, I should rstrip and split in the loop and than sort the list. I think I should append the list in the loop before sorting it.
 fname = input("Enter file name: ")
fh = open(fname)
lst = list(fh)
for line in lst:
    line = line.rstrip()
    print line
    y = line.split()
    I = lst.append()
 
k = y.sort()
print y
I will appreciate if anyone has a fix for my code...
Thanks to all those who viewed my code. I have managed to fix the error and outputted the excepted results. This is how the code should be to output the words in the list in alphabetical order.
name = input('Enter file: ')
handle = open(name, 'r')
wordlist = list()
for line in handle:
    words = line.split()
    for word in words:
        if word in wordlist: continue
        wordlist.append(word)

wordlist.sort()
print(wordlist)