Joining byte list with python

PythonListJoinByte

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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'

Solution 2 - Python

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()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2130898View Question on Stackoverflow
Solution 1 - PythonAndrew ClarkView Answer on Stackoverflow
Solution 2 - PythonmawimawiView Answer on Stackoverflow