Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining byte list with python

I'm trying to develop a tool that read a binary file, makes some changes and save it. What I'm trying to do is make a list of each line in the file, work with several lines and then join the list again.

This is what I tried:

file = open('myFile.exe', 'r+b')  aList = [] for line in f:     aList.append(line)  #Here im going to mutate some lines.  new_file = ''.join(aList) 

and give me this error:

TypeError: sequence item 0: expected str instance, bytes found 

which makes sense because I'm working with bytes.

Is there a way I can use join function o something similar to join bytes? Thank you.

like image 396
user2130898 Avatar asked Jun 12 '13 14:06

user2130898


People also ask

Can you concatenate bytes in Python?

Concatenating many byte strings In case you have a longer sequence of byte strings that you need to concatenate, the good old join() will work in both, Python 2.7 and 3. x. In Python 3, the 'b' separator string prefix is crucial (join a sequence of strings of type bytes with a separator of type bytes).

What does byte () do in Python?

Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.

What is Bytearray data type in Python?

The bytearray type is a mutable sequence of integers in the range between 0 and 255. It allows you to work directly with binary data. It can be used to work with low-level data such as that inside of images or arriving directly from the network. Bytearray type inherits methods from both list and str types.


2 Answers

Perform the join on a byte string using b''.join():

>>> b''.join([b'line 1\n', b'line 2\n']) b'line 1\nline 2\n' 
like image 190
Andrew Clark Avatar answered Oct 02 '22 16:10

Andrew Clark


Just work on your "lines" and write them out as soon as you are finished with them.

file = open('myFile.exe', 'r+b') outfile = open('myOutfile.exe', 'wb')  for line in f:     #Here you are going to mutate the CURRENT line.     outfile.write(line) file.close() outfile.close() 
like image 31
mawimawi Avatar answered Oct 02 '22 16:10

mawimawi