Home > Enterprise >  sort text file and and sort the number of listing
sort text file and and sort the number of listing

Time:08-16

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')

CodePudding user response:

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:

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

Process finished with exit code 0
  • Related