读取并附加到同一个文本文件

Reading and appending to the same text file

我有一个程序可以将串行数据写入文本文件。我想首先通过读取文件来检查文本文件中的特定卡 UID,如果已经有卡 UID 我想跳过串行写入步骤(串行写入 0),如果没有那个卡 UID 我会继续并串行写入 1.

为了检查卡的 UID,我使用了下一个命令,请查看我的代码。

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 线程是我需要帮助的。同样,我想首先读取文本文件(创建时最初为空)并检查带有卡 UID 的行,并查看文件中是否已经存在该特定卡 UID(如果没有则写入 0)连续写1.

但是运行这段代码给我一个错误:

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

由于每次 运行 您的程序都会重新创建空的 uid.txt 文件,因此您不需要文件来保存信息。只需使用 set 代替:

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