Split and sort input file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Split and sort input file (/thread-25705.html) |
Split and sort input file - aawaleh - Apr-08-2020 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 RE: Split and sort input file - TomToad - Apr-09-2020 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. RE: Split and sort input file - aawaleh - Apr-09-2020 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 RE: Split and sort input file - aawaleh - Apr-10-2020 I will appreciate if anyone has a fix for my code... RE: Split and sort input file - aawaleh - Apr-10-2020 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) |