写二进制整数或字符串在Python文件 [英] Write a binary integer or string to a file in python

查看:326
本文介绍了写二进制整数或字符串在Python文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串(可以是一个整数太)在Python,我想将它写入文件。它仅包含一和零欲一和零的这种模式将被写入到文件中。我想直接写二进制,因为我需要存储大量的数据,但只有特定的值。我认为没有必要占用使用每值八位时,我只需要三个空间。

I have a string (it could be an integer too) in Python and I want to write it to a file. It contains only ones and zeros I want that pattern of ones and zeros to be written to a file. I want to write the binary directly because I need to store a lot of data, but only certain values. I see no need to take up the space of using eight bit per value when I only need three.

有关实例。比方说,我写的二进制字符串01100010到一个文件中。如果我在一个文本编辑器中打开它,它会说 B (01100010是ASCII code为B)。不要混淆虽然。我不想写ASCII codeS,这个例子只是为了说明,我想直接写入字节的文件。

For instance. Let's say I were to write the binary string "01100010" to a file. If I opened it in a text editor it would say b (01100010 is the ascii code for b). Do not be confused though. I do not want to write ascii codes, the example was just to indicate that I want to directly write bytes to the file.

澄清:

我的字符串看起来是这样的:

My string looks something like this:

binary_string = "001011010110000010010"

这不是由二进制codeS的数字或字符。它包含了相关的数据只到我的计划。

It is not made of of the binary codes for numbers or characters. It contains data relative only to my program.

推荐答案

好吧,之后相当多的搜索,我找到了答案。我相信,剩下的你根本不明白(这可能是我的错,因为我不得不修改两次,说清楚)。我发现它<一个href=\"http://www.linuxquestions.org/questions/programming-9/writing-binary-data-under-python-718165/\"相对=nofollow>这里。

Alright, after quite a bit more searching, I found an answer. I believe that the rest of you simply didn't understand (which was probably my fault, as I had to edit twice to make it clear). I found it here.

答案是拆分每一块数据,将它们转换成二进制整数,然后把它们放在一个二进制数组。之后,你可以使用数组的 TOFILE()方法写入到文件中。

The answer was to split up each piece of data, convert them into a binary integer then put them in a binary array. After that, you can use the array's tofile() method to write to a file.

from array import *

bin_array = array('B')

bin_array.append(int('011',2))
bin_array.append(int('010',2))
bin_array.append(int('110',2))

f = file('binary.mydata','wb')
bin_array.tofile(f)
f.close()

这篇关于写二进制整数或字符串在Python文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆