用python加入字节列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17068100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:20:55  来源:igfitidea点击:

Joining byte list with python

pythonlistjoinbyte

提问by user2130898

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.

有没有办法可以使用连接函数 o 类似于连接字节的东西?谢谢你。

采纳答案by Andrew Clark

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

使用b''.join()以下方法对字节字符串执行连接:

>>> b''.join([b'line 1\n', b'line 2\n'])
b'line 1\nline 2\n'

回答by mawimawi

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