本文介绍了Python如何写入二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个作为整数的字节列表,类似于

[120, 3, 255, 0, 100]

如何将此列表作为二进制文件写入文件?

这行得通吗?

newFileBytes = [123, 3, 255, 0, 100]#制作文件newFile = open("文件名.txt", "wb")# 写入文件newFile.write(newFileBytes)
解决方案

这正是 bytearray 用于:

newFileByteArray = bytearray(newFileBytes)newFile.write(newFileByteArray)

如果您使用的是 Python 3.x,则可以使用 bytes 代替(并且可能应该这样做,因为它可以更好地表明您的意图).但是在 Python 2.x 中,这是行不通的,因为 bytes 只是 str 的别名.像往常一样,用交互式解释器显示比用文本解释更容易,所以让我这样做.

Python 3.x:

>>>字节数组(新文件字节)bytearray(b'{\x03\xff\x00d')>>>字节(新文件字节)b'{\x03\xff\x00d'

Python 2.x:

>>>字节数组(新文件字节)bytearray(b'{\x03\xff\x00d')>>>字节(新文件字节)'[123, 3, 255, 0, 100]'

I have a list of bytes as integers, which is something like

[120, 3, 255, 0, 100]

How can I write this list to a file as binary?

Would this work?

newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
newFile.write(newFileBytes)
解决方案

This is exactly what bytearray is for:

newFileByteArray = bytearray(newFileBytes)
newFile.write(newFileByteArray)

If you're using Python 3.x, you can use bytes instead (and probably ought to, as it signals your intention better). But in Python 2.x, that won't work, because bytes is just an alias for str. As usual, showing with the interactive interpreter is easier than explaining with text, so let me just do that.

Python 3.x:

>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
b'{\x03\xff\x00d'

Python 2.x:

>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'

这篇关于Python如何写入二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 01:23