Python Forum
Sorting Text within a .txt file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting Text within a .txt file
#1
Hey everyone,

So I am running into an issue with a code where I cant figure out how to sort text within a txt file. So the question states:

"Write a program that reads the student ID, name, and major from each student in "students.txt.", sorts, students information in ascending order according to their ID number and updates students.txt with the sorted results.

The text file will look like this:
123456789
Jane Doe
Math
23456781
John Doe
Science
345678912
Joe Doe
Geography
etccc

So far I have been able to open and read the text, and write it to a file. I can sort the text, however not how it needs to be. When I sort the text, all the student ID's are listed in ascending order, then students and then majors. I Cant figure out how to group the three lines together and sort them all that way. Below is my code.

def main():
    inputFile = open("students.txt", 'r')
    lineList = inputFile.readlines()
    lineList.sort()
    print (lineList)
    for line in  lineList:
        print(line)
        with open('students.txt', 'a') as f:
            for line in lineList:
                lineList.sort()
                f.write(line)



main()
This question is not a homework question, it is a question on a final review sheet. My final is tomorrow, any help would be much appreciated thank you everyone and happy holidays!
Reply


Messages In This Thread
Sorting Text within a .txt file - by drogers10940 - Dec-15-2017, 10:32 PM
RE: Sorting Text within a .txt file - by squenson - Dec-15-2017, 10:43 PM
RE: Sorting Text within a .txt file - by wavic - Dec-15-2017, 11:16 PM
RE: Sorting Text within a .txt file - by wavic - Dec-15-2017, 11:30 PM
RE: Sorting Text within a .txt file - by squenson - Dec-16-2017, 06:27 AM
RE: Sorting Text within a .txt file - by squenson - Dec-16-2017, 04:23 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Convert text from an image to a text file Evil_Patrick 5 4,474 Jul-30-2019, 07:57 PM
Last Post: DeaD_EyE
  reading text file and writing to an output file precedded by line numbers kannan 7 10,701 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  Sorting File Miraclefruit 1 3,492 Apr-16-2017, 01:28 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

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