Joining byte list with python

女生的网名这么多〃 提交于 2019-12-20 11:04:24

问题


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.


回答1:


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'



回答2:


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


来源:https://stackoverflow.com/questions/17068100/joining-byte-list-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!