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
  Count & Sort occurrences of text in a file oradba4u 7 303 Sep-06-2020, 03:23 PM
Last Post: oradba4u
  How to assign input file name as logger name Mekala 5 391 Aug-05-2020, 12:54 AM
Last Post: Larz60+
  Read/Sort Large text file avoiding line-by-line read using mmep or hdf5 Robotguy 0 363 Jul-22-2020, 08:11 PM
Last Post: Robotguy
  User Input and CSV File Davy_Jones_XIV 2 879 Mar-24-2020, 08:43 AM
Last Post: Davy_Jones_XIV
  How to sort image files according to a metadata file? Brahmslove 1 637 Dec-05-2019, 11:25 PM
Last Post: scidam
  input string split Eric7Giants 3 754 Nov-13-2019, 07:19 PM
Last Post: Gribouillis
  Split csv file based on column value soli004 4 1,948 Oct-22-2019, 05:53 AM
Last Post: soli004
  [split] NameError: name 'lo' is not defined when using input ? Cedmo 2 910 Jul-05-2019, 09:39 PM
Last Post: Cedmo
  split file mcgrim 1 511 May-22-2019, 08:36 PM
Last Post: DeaD_EyE
  "Split" file and comparison with CSV morgandebray 14 2,027 Aug-07-2018, 10:22 AM
Last Post: morgandebray

Forum Jump:

User Panel Messages

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