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
Sad How to split a String from Text Input into 40 char chunks? lastyle 7 1,054 Aug-01-2023, 09:36 AM
Last Post: Pedroski55
  How to "tee" (=split) output to screen and into file? pstein 6 1,289 Jun-24-2023, 08:00 AM
Last Post: Gribouillis
  Split pdf in pypdf based upon file regex standenman 1 1,974 Feb-03-2023, 12:01 PM
Last Post: SpongeB0B
Question Take user input and split files using 7z in python askfriends 2 1,028 Dec-11-2022, 07:39 PM
Last Post: snippsat
  How to sort .csv file test log which item first fail and paint color SamLiu 24 4,702 Sep-03-2022, 07:32 AM
Last Post: Pedroski55
  How to split the input taken from user into a single character? mHosseinDS86 3 1,137 Aug-17-2022, 12:43 PM
Last Post: Pedroski55
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,277 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  Reading an Input File DaveG 1 1,213 Mar-27-2022, 02:08 AM
Last Post: deanhystad
  How to split file by same values from column from imported CSV file? Paqqno 5 2,705 Mar-24-2022, 05:25 PM
Last Post: Paqqno
  [split] Results of this program in an excel file eisamabodian 1 1,543 Feb-11-2022, 03:18 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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