Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Split and sort input file
#1
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
Reply
#2
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.
Reply
#3
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
Reply
#4
I will appreciate if anyone has a fix for my code...
Reply
#5
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Help- converting file with pyton script eltomassito 6 446 Jul-02-2021, 05:29 PM
Last Post: snippsat
  Sort data from JSON file Dummy_in_programming 2 549 Jan-04-2021, 06:17 PM
Last Post: deanhystad
  Split Characters As Lines in File quest_ 3 665 Dec-28-2020, 09:31 AM
Last Post: quest_
  [split] How to convert the CSV text file into a txt file Pinto94 5 698 Dec-23-2020, 08:04 AM
Last Post: ndc85430
  Count & Sort occurrences of text in a file oradba4u 7 865 Sep-06-2020, 03:23 PM
Last Post: oradba4u
  How to assign input file name as logger name Mekala 5 818 Aug-05-2020, 12:54 AM
Last Post: Larz60+
  User Input and CSV File Davy_Jones_XIV 2 2,431 Mar-24-2020, 08:43 AM
Last Post: Davy_Jones_XIV
  How to sort image files according to a metadata file? Brahmslove 1 1,303 Dec-05-2019, 11:25 PM
Last Post: scidam
  input string split Eric7Giants 3 1,223 Nov-13-2019, 07:19 PM
Last Post: Gribouillis
  Split csv file based on column value soli004 4 3,395 Oct-22-2019, 05:53 AM
Last Post: soli004

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020