nani92 nani92 - 1 day ago 4
Python Question

How to send the result data to file text?

I am trying to send the resulted data from a python script to a file text.

import string
import serial
import time
from array import array
import struct
import binascii
ser = serial.Serial(
port='COM4',\
baudrate=230400,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
text_file = open('C:\\Users\\user\\Ciphertxt.txt', 'w')
f = open(r'C:\\Users\\user\\Plaintxt.txt', 'r')
for a in f:
plaintxt_16b=a[0:32]
plaintext=binascii.unhexlify(plaintxt_16b)
clear_msg=b'\x24'+b'\x73'+b'\x10'+plaintext
ser.write(clear_msg)
time.sleep(0.5)
print(ser.read(156))
text_file.write(ser.read(156))
ser.close() # close ports


This line
print(ser.read(156))
already displayed for me the good data, so I am sure about results which is:

*************************
e0370734 313198a2 885a308d 3243f6a8
Go encrypt..
Encrypt done..
196a0b32 dc118597 2dc09fb 3925841d
***********************
*************************
ccddeeff 8899aabb 44556677 112233
Go encrypt..
Encrypt done..
d6e4d64b 27d8d055 c5c7573a 8df4e9aa
***********************
*************************
54776f20 4f6e6520 4e696e65 2054776f
Go encrypt..
Encrypt done..
155d4a8c 17d78b93 409745dd e73be537
***********************


But the Ciphertxt.txt file just gives me those three lines.

**

**

**


I don't understand where the problem is.

Answer

Once you read the data from ser.read(156), that data is removed from ser and it won't be available to you again.

So, reading that data twice can either give you garbage data or not give any data at all.

You should store it in a variable. The following code would work just fine.

data = ser.read(156)
print data
text_file.write(data)
Comments