Dec-15-2017, 10:32 PM
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.
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!