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
#2
You should:
1. Read three lines,
2. Store the values in tuple
3. Store the tuple in an array
4. Repeat 1, 2 and 3 until the end of the file
5. Sort the array of tuples
6. Write the output file
Reply
#3
Well, @squenson gave you the answer. Don't forget that if you loop over an iterator it remembers the last position.
for _ in [1,2,3]:
    read a line
    etc . 
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
Wavic,

To meet the first requirement for reading the lines 1-3 I was thinking the following:

import itertools
with open(students.txt, "r") as text_file:
    for line in itertools.islice(text_file,0,2):
I am trying to work on taking the line and then putting it in a tuple for that I am thinking

my_tuple = [line]


and then to step to the next 3 lines to read and store would I just use another for loop with line =+1?
Reply
#5
It's better to use the simplest way. Except when cost you performance but this almost never happens. If it works, use what you like more.  Smile
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#6
So I came up with this following code, please bear with me if it is terrible. But its not giving me any syntax errors and seems to be running. When I re-open the text file to view the newly sorted results, the text file is empty. Is this because I am "w" and not "a"?

import itertools
def main():
    inputFile= open("students.txt", 'r')
    lineList = inputFile.readlines()
    with open("students.txt", "r") as text_file:
        for line in itertools.islice(text_file,0,2):
            my_tuple = (line)
            for n in my_tuple:
                sorted(my_tuple)
                inputFile.close()
                with open("students.txt", "w") as text_file:
                    text_file.write(my_tuple)
                    close.inputFile()
main()
Reply
#7
So this set of code will write into the text file, but it only writes in the first three lines of the original text file. It actually didnt sort them to ascending order either. Any words on why this might be?
Reply
#8
If you carefully re-read my initial post, you will notice that the steps 5 and 6 are only executed when the input file has been fully processed. In your code, the for loop includes some sorting and output file writing...

Second hint: you sort elements of the tuple itself -- (123456789, "John Doe", "Math") -- is this really what you want?
Reply
#9
Squenson,

That is how I would like to be able to sort it, but I cannot figure that out. But then I will also have to sort out every other three lines and I am having trouble figuring that out as well. If 5 & 6 should be processed after the input file has been, should I put them in a separate function and then call that function? Would that make sense?
Reply
#10
And what about step 3?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Convert text from an image to a text file Evil_Patrick 5 4,216 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,244 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  Sorting File Miraclefruit 1 3,387 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