Issue
So I am working on a school assignment where I have to code a server (using C) and a client (using python).
The client has to be able to accept commands such as "put-cfg" which makes it send his boot file to the server. In order to send the file I have been told to use a given pdu where the "data" part of the package contains exactly 150 bytes. So to make it work, at some point I have to read the boot file and split it in 150 byte chunks (or directly read it on 150 byte pieces).
I know that by using .read(size)
I can choose how many bytes I want to read from the file, but my problem is that, even though I know how to read a file until it's end (by using typical for line in file:
) I don't know how to read it in a given size (150 bytes) until I reach the end of the file. I would approach it somehow like this:
stream = []
stream += [file.read(150)]
for stream in file:
stream += [file.read(150)]
I would do it like that in order to have the file saved in a "150 byte of file" array so I can send each of the array positions on the pdu.
The problem I see is that I don't think the for stream in file:
is going to work, that's what I am not able to do, reading the file in 150 byte chunks until it ends, how do I know I have reached the end?
First time posting here, I have tried my best to not make it a stupid question, any help would be appreciated.
PD: The boot file is a text file.
Solution
If you reach the end-of-line, you will just get an empty string. The last block before the end-of-line will have the rest of the characters, so if 120 characters were left, you will get a 120-character string even if the block size is 150).
So, we can just put your code in an infinite loop, breaking it when the string is empty.
stream = []
while True:
block = file.read(150)
if not block:
break
stream += [block]
Answered By - ProblemsLoop Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.