title: Reading and appending to the same text file
body: <p>I have a program that writes serial data to the text file. I want to check for specific card UIDs in the text file by reading the file at first, if there is already a card UID I want to skip the serial write step (serial write 0), if there isn't that card UID I will go ahead and serial write 1.</p>
  <p>In order to check for card UIDs I have employed next command, please have a look at my code.</p>
  <pre><code>import threading
  import serial
  import sys
  import io
  import codecs
  import queue
  from pynput import keyboard
  
  with io.open(&quot;uid.txt&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;) as b:
      b.write(&quot;&quot;)
  
  q = queue.Queue()
  ser = serial.Serial('COM4', baudrate = 9600, timeout = 5)
  
  class SerialReaderThread(threading.Thread):
      def run(self):
          while True:
              output = ser.readline().decode('utf-8')
              print(output)
              q.put(output)
  
  
  class FileWriting(threading.Thread):
     def run(self):
         while True:
             output = q.get() 
             with io.open(&quot;uid.txt&quot;, &quot;r+&quot;, encoding=&quot;utf-8&quot;) as input:
                 for line in input:
                     if line.startswith(&quot;Card UID: &quot;):
                         s = (next(input))
                         if line.startswith(s): ***
                             ser.write(b'0\r\n')
                         else:
                             ser.write(b'1\r\n')
             with io.open(&quot;uid.txt&quot;, &quot;a+&quot;, encoding=&quot;utf-8&quot;) as f:
                 f.write(output)
                    
  
  serial_thread = SerialReaderThread()
  file_thread=FileWriting()
  
  serial_thread.start()
  file_thread.start()
  
  serial_thread.join()
  file_thread.join()
  </code></pre>
  <p><strong>FileWriting</strong> thread is what I need help with. Again I want to first read the text file (which initially will be empty as it is created) and check for lines with card UID and look if there already is that specific card UID in the file if there is write 0 if there isn't write 1 in serial.</p>
  <p>However running this code gives me an error:</p>
  <pre><code>Exception in thread Thread-2:
  Traceback (most recent call last):
    File &quot;C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\threading.py&quot;, line 932, in _bootstrap_inner
      self.run()
    File &quot;C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\project\fff.py&quot;, line 36, in run
      s = (next(input))
  StopIteration
  </code></pre>