Search code examples
pythonfilepyserialfile-writing

Reading and appending to the same text file


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.

In order to check for card UIDs I have employed next command, please have a look at my code.

import threading
import serial
import sys
import io
import codecs
import queue
from pynput import keyboard

with io.open("uid.txt", "w", encoding="utf-8") as b:
    b.write("")

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("uid.txt", "r+", encoding="utf-8") as input:
               for line in input:
                   if line.startswith("Card UID: "):
                       s = (next(input))
                       if line.startswith(s): ***
                           ser.write(b'0\r\n')
                       else:
                           ser.write(b'1\r\n')
           with io.open("uid.txt", "a+", encoding="utf-8") as f:
               f.write(output)
                  

serial_thread = SerialReaderThread()
file_thread=FileWriting()

serial_thread.start()
file_thread.start()

serial_thread.join()
file_thread.join()

FileWriting 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.

However running this code gives me an error:

Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\project\fff.py", line 36, in run
    s = (next(input))
StopIteration

Solution

  • Since you re-create the uid.txt file empty each time you run your program, you don't need a file to hold the information. Just use a set instead:

    ser = serial.Serial('COM4', baudrate = 9600, timeout = 5)
    
    class SerialReaderThread(threading.Thread):
        def run(self):
            uids = set()
            while True:
                output = ser.readline().decode('utf-8')
                print(output)
                response = b'0' if output in uids else b'1'
                ser.write(response + b'\r\n')
                uids.add(output)
    
    serial_thread = SerialReaderThread()
    
    serial_thread.start()
    
    serial_thread.join()