Python 读取和附加到同一文本文件
我有一个将串行数据写入文本文件的程序。我想首先通过读取文件来检查文本文件中的特定卡UID,如果已经有卡UID,我想跳过串行写入步骤(串行写入0),如果没有卡UID,我将继续串行写入1 为了检查卡UID,我使用了下一个命令,请查看我的代码Python 读取和附加到同一文本文件,python,file,pyserial,file-writing,Python,File,Pyserial,File Writing,我有一个将串行数据写入文本文件的程序。我想首先通过读取文件来检查文本文件中的特定卡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.
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()
文件写入线程是我需要的帮助。同样,我想首先读取文本文件(在创建文本文件时,该文件最初将为空),并检查是否有包含卡UID的行,如果文件中存在写入0,如果串行中没有写入1,则查看文件中是否已经存在该特定卡UID
但是,运行此代码会给我一个错误:
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
文件重新创建为空,因此不需要文件来保存信息。只需使用集合
:
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()
您的意思是要检查
output
是否是保存在UID.txt
文件中的UID
?并将它们全部收集到uid.txt
文件中?很抱歉,如果我把你弄糊涂了,我会尽力解释得更好。串行信息保存在uid.txt
文件中,串行端口上有许多卡正在扫描每个卡都有其唯一的卡uid
,我主要想检查卡是否已经扫描过,这样代码就不允许对同一卡串行写入1两次。我基本上需要检查文本文件中是否已经有特定的卡片UID。那么为什么需要一个文件呢?你能记住这些信息吗?我只是觉得这是最简单的方法。但我会采纳您的任何建议。谢谢您的回复,我测试了代码,但扫描时它仍将b'1\r\n'
写入同一张卡,我还将发布串行输出,这样可能会更清晰一些。这是串行输出,我想检查UID,但该代码允许同一卡写入串行1<代码>扫描MIFARE经典FF卡UID:F9 08 A3 99 PICC类型:MIFARE 1KB使用密钥进行身份验证。。。正在将数据写入块22。。。00 2E 00 00 00 00 00不同卡之间唯一串行变化的是卡UID
其余部分保持不变…您需要一种从该数据中提取卡UID的方法。我觉得一个新的问题来了。一点也不,我按照你说的做了,我把数据减少到只有卡UID,以及它是否成功写入1。这是我的新串行数据,但它仍然会向同一张卡写入两次或更多次,在写入6或7次后,它只向所有卡写入0<代码>卡片UID:F9 08 A3 99成功卡片UID:F9 08 A3 99成功这是将同一张卡片放入写入器两次时的串行输出。无需担心,老兄,我已经修复了它。非常感谢您让我的工作变得轻松,帮助解决了我的问题,我所做的只是将数据减少到只有卡片UID,然后它就工作了。非常感谢!