Python:1 和 0 组成的字符串 ->二进制文件
我在 Python 中有一个由 1 和 0 组成的字符串,我想将其写入二进制文件。我在寻找一个好方法来做到这一点时遇到了很多麻烦。
有没有一种我只是缺少的标准方法可以做到这一点?
I have a string of 1's and 0's in Python and I would like to write it to a binary file. I'm having a lot of trouble with finding a good way to do this.
Is there a standard way to do this that I'm simply missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您想要一个二进制文件,
这是您正在寻找的吗?
If you want a binary file,
Is this what you are looking for?
将输入拆分为八位,然后应用
int(_, 2)
和chr
,然后连接成一个字符串并将该字符串写入文件。像...的东西:
Split your input into pieces of eight bits, then apply
int(_, 2)
andchr
, then concatenate into a string and write this string to a file.Something like...:
现在有一个 bitstring 模块可以满足您的需要。
您可以使用 xxd -b file.bin 在 Linux 的 shell 中测试它
There is a bitstring module now which does what you need.
You can test it from the shell in Linux with
xxd -b file.bin
或者您可以像这样使用
array
模块Or you can use the
array
module like this