77

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.

4
  • 1
    for what it's worth, you could do aList = f.readlines() or aList = list(f) Commented Jun 12, 2013 at 14:29
  • Try: new_file = '\x01'.join(aList) Commented Jun 12, 2013 at 14:30
  • 4
    Does it make sense to talk about "lines" in a binary file? Usually we add newlines for legibility, and that doesn't apply to binary files. I wonder if you'd be better off working with fixed-length strings, like every 80 bytes. (Just a thought.) Commented Jun 12, 2013 at 14:33
  • 1
    @sea-rob PDFs for example are a weird mishmash of text and binary format, where sometimes line breaks matter and you can have bytes that don't form valid UTF-8. Commented Aug 21, 2023 at 6:54

2 Answers 2

150

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'
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

I didn't think about this solution, this is much easier than mine. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.