nani92 nani92 - 5 days ago 5
Python Question

How to iterate lines from a text file in python?

I am trying to read lines from a text file"Plaintext.txt".

e0370734313198a2885a308d3243f6a8
ccddeeff8899aabb4455667700112233
8e73b0f7da0e6452c810f32bc4567a22


It contains now tow lines, I put just two in order to make simple test, but I must put more then 1000 texts (means more than 1000 lines) I want to read each line then send it to the uart where I will do encryption for every plaintext (The encryption algorithm is in C): This is my script:

I edit it as you tell me but I still have the encryption of one line

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)

f = open(r'C:\\Users\\msmache\\Win_My_Scripts\\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.4)

while True:
print(ser.read(70))
ser.close() # close ports


In the C file:

uint8_t rx_buffer[19];
//unsigned int plaintext[4];
dev_uart_ptr->uart_open(230400, 1, 0);
memset(rx_buffer, 0, sizeof(rx_buffer));
while(1)
{
int rx_length = dev_uart_ptr->uart_read((void*)rx_buffer, 19);

if (rx_length <19) // 19 is the number of bytes in each received line
{
......

//encryption
.....
}

}// End While


So the problem is that It takes just the last line and repeat all the time the encryption of that line:

$sÄs░¸┌dR╚¾+─Vz"
**************************
8e73b0f7 da0e6452 c810f32b c4567a22
Go e
ncrypt..
Encrypt done..
aed2a303 4809119f 136646ba 56a2c588
******
********************
**************************
8e73b0f7 da0e6452 c8
10f32b c4567a22
Go encrypt..
Encrypt done..
aed2a303 4809119f 1366
46ba 56a2c588
**************************
**************************

8e73b0f7 da0e6452 c810f32b c4567a22
Go encrypt..
Encrypt done..

aed2a303 4809119f 136646ba 56a2c588
**************************
****
**********************
8e73b0f7 da0e6452 c810f32b c4567a22
Go encry
pt..
Encrypt done..
aed2a303 4809119f 136646ba 56a2c588


I would be very grateful if you could help me.

Answer

You may want to do as following:

f = open("your_file", "r")
for line in f:
    do_something(line)
f.close()

or as the comment pointed out:

with open("your_file", "r"):
    for line in f:
        do_something(line)

Python will iterate over every line and give the string of the line as variable line here. You can handle every line in the file this way. Also, doing so, python reads one line each time, so it is effective for larger files.

Comments