Python - What is the most efficient way to create add-ons?

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.

+4
source share
4 answers

Could you just use ljust() to make the addition, since we are dealing with string objects here?

 bytes = f.read(self.chunksize) if bytes: bytes = bytes.ljust(self.chunksize, '\0') 
+12
source
 bytes += "\0"*len_diff 

should help

+2
source

try it.

 bytes = "\0" * self.chunksize rbytes = f.read(self.chunksize) bytes[:len(rbytes)] = rbytes 

or

 bytes = f.read(self.chunksize) bytes += "\0" * (self.chunksize - len(bytes)) 
+2
source

What about:

 bytes += "\0"*len_diff 
+2
source

All Articles