I just started learning threads in Python. Here is the task: The main program thread should generate random content lines and put them at the end of the list. Child stream # 1 should display the current state of the list on the screen. Child stream # 2 wakes up every five seconds and sorts the list in lexicographical order and saves it to a file. Everything works, except for writing to the file. Tell me, please, what's the problem?

import threading import time from random import choice from string import ascii_letters def sortirovka(): f = open("qw.txt", "w") while 4 > 0: time.sleep(5) spicok.sort(key=str.lower) f.write(str(spicok)) def printer(): f = open("qw.txt", "r") while 4 > 0: print(spicok) time.sleep(1) spicok = [] t = threading.Thread(target=sortirovka) p = threading.Thread(target=printer) t.start() p.start() while 4 > 0: spicok.append(''.join(choice(ascii_letters) for i in range(12))) time.sleep(1) 

    2 answers 2

    In the next answer, everything was correctly written about the fact that after recording the files need to be closed. The error of that answer is that there is no point in wrapping an endless loop in the context manager, since program execution never comes to file closure.

    The file must be opened and closed at each iteration. That is, if a context manager is used, then it must be entirely inside the loop:

     def sortirovka(): while 4 > 0: time.sleep(5) with open("qw.txt", "w") as f: spicok.sort(key=str.lower) f.write(str(spicok)) 

    And in the function printer in general, there is no point in opening the file, since there you are not using it.

      The record most likely also works, just the file does not close, there is no f.close() in the code.

      In order not to forget to close the file, you can use the context manager :

       with open("qw.txt", "w") as f: while 4 > 0: time.sleep(5) spicok.sort(key=str.lower) f.write(str(spicok)) 
      • Thank you, but did not help ( - Ilyas Nugaev