Here's the problem: I read binaries in fairly large blocks (512 KiB) and wish to fill the last block with zeros whenever it is shorter than the block size.
I am currently doing something like this:
bytes = f.read(self.chunksize) if len(bytes) > 0: len_diff = self.chunksize - len(bytes) if len_diff > 0: bytes += reduce(lambda x,y: x+y, ["\0" for i in range(0, len_diff)])
Obviously, this is terribly inefficient, as this reduction will result in a lot of string concatenations. I am wondering how can I achieve this using Python? In C, I just calloc and do with it.
If this is not possible for Python, I am ready to convert this code to a C module and / or completely abandon Python for this project, since it is still in its early stages.
Hooray!
EDIT . I feel terrible, not forgetting to use the * operator. :-)
This solution worked fine for me:
bytes += "\0" * len_diff
EDIT No. 2 . Using ljust (), I simplified my code a bit, so the correct answer will be passed to Jeff.
source share