sort text file and and sort the number of listing

Question:

I want to sort a text file every time a new input was added, but I want the numbers for each name also get sorted. but when I used split() I get errors : I/O operation on closed file.
am I putting it in a wrong place? or should I not reread the lines. I tried to just add file.sort() at the end but since each line start with number and it was already sorted in that way.

while True:

file = open('s:/not a test.txt','r')
lst = file.readlines()

file.close()
n = input("enter name and familyname: ")
if n:
    length = len(lst)+1
    file = open('s:/not a test.txt','a')
    
    file.write(str(length)+'. '+n+'n')
    file.close()
else:
    break
eachline = file.readlines()
data = eachline.split(".")
lines.sort()
for line in lst:
    file.write(str(length)+'. '+n+'n')
Asked By: Fox Black

||

Answers:

The error says that your file is closed and you are tyring to sort values of a closed file.
Here is the alternative. You may adapt this one to yours:

I open the file in read+ mode which is what you could use to append the content. I am using with open instead of just open so that I do not need to force close the file myself. It takes care by itself when the act is done.
When the file is read its content, the code executes the input method and it iterates in the while loop until you do not enter anything and goes into the else part of the decision when you do not enter anything. As you enter the else part, the list is then sorted and printed out and the loop breaks out.

while True:
    with open('one.txt', 'r+') as file:
        lst = file.readlines()
        print(lst)
        n = input("number")
        if n:
            ln = len(lst)+1
            file.write(n + 'n')
            # eachline = file.readlines()
        else:
            print(list)
            sortedlines = sorted(lst)
            print(sortedlines)
            break

here is the output that I got:

['1n', '4n', '3n']
number8
['1n', '4n', '3n', '8n']
number7
['1n', '4n', '3n', '8n', '7n']
number
<class 'list'>
['1n', '3n', '4n', '7n', '8n']

Process finished with exit code 0
Answered By: Anand Gautam

so I made some changes from the information and help that I got here from Anand Gautam. thank you so much.

while True:

with open ('s:/not a test.txt', 'r') as file:
    lst = file.readlines()
    n = input("enter name and familyname: ")
    if n:
        file.write(n+'n')
    else:
        count= 1
        m = sorted(lst)
        with open ('s:/not a test.txt', 'w') as f:
            for eachline in m:
                file.write(str(count)+'.'+ eachline+'n')
                count+=1
        

        break

so, I brought the sorting and numbering part after the inputs have finished. it will get the new inputs and everything and then sort the text file. I’m not sure if it will have problem but this is close to what I had in mind.

Answered By: Fox Black