Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中将单个位写入文本文件?_Python_File Io - Fatal编程技术网

如何在python中将单个位写入文本文件?

如何在python中将单个位写入文本文件?,python,file-io,Python,File Io,假设我有一个像824这样的数字,我使用python将其写入一个文本文件。在文本文件中,它将占用3个字节的空间。但是,如果我用位表示它,它有以下表示0000001100111000,即2字节(16位)。我想知道如何用python将位写入文件,而不是字节。如果我可以这样做,文件的大小将是2字节,而不是3字节。 请提供代码。我正在使用python 2.6。另外,我不想使用基本安装中没有的任何外部模块 我在下面试了一下,给了我12个字节 a =824; c=bin(a) handle = open('t

假设我有一个像824这样的数字,我使用python将其写入一个文本文件。在文本文件中,它将占用3个字节的空间。但是,如果我用位表示它,它有以下表示0000001100111000,即2字节(16位)。我想知道如何用python将位写入文件,而不是字节。如果我可以这样做,文件的大小将是2字节,而不是3字节。 请提供代码。我正在使用python 2.6。另外,我不想使用基本安装中没有的任何外部模块 我在下面试了一下,给了我12个字节

a =824;
c=bin(a)
handle = open('try1.txt','wb')
handle.write(c)
handle.close()

我认为您想要的是以二进制模式保存文件:

open("file.bla", "wb")
但是,这将向文件写入一个整数,其大小可能为4字节。我不知道Python是否有一个2字节的整数类型。但您可以通过在一个32位数字中编码2个16位数字来避免这种情况:

a = 824
b = 1234
c = (a << 16) + b
a=824
b=1234
c=(a看看:

模块就是您想要的。根据您的示例,824=000000 1100111000二进制或0338十六进制。这是两个字节03H和38H。将824转换为这两个字节的字符串,但您还必须决定小端(先写38H)或大端(先写03H)

例子
你能详细说明一下上面的内容吗?比如说,用一些关于如何将824转换成二进制格式并以“按位”方式写入文件的代码,也就是说,在文件中它应该占用2个字节,而不是3个字节,但是,比如说5个字节,我可以用1个字节来表示它。在这种情况下,我不需要2个字节。解决方法是什么?我想使用最小字节数来读取数据结构文档。如果值适合一个字节,则使用B而不是H。
>>> struct.pack("h", 824)
'8\x03'
>>> import struct
>>> struct.pack('>H',824) # big-endian
'\x038'
>>> struct.pack('<H',824) # little-endian
'8\x03'
>>> struct.pack('H',824)  # Use system default
'8\x03'
import struct

a = 824
bin_data = struct.pack('<H',824)
print 'bin_data length:',len(bin_data)

with open('data.bin','wb') as f:
    f.write(bin_data)

with open('data.bin','rb') as f:
   bin_data = f.read()
   print 'Value from file:',struct.unpack('<H',bin_data)[0]

print 'bin_data representation:',repr(bin_data)
for i,c in enumerate(bin_data):
    print 'Byte {0} as binary: {1:08b}'.format(i,ord(c))
bin_data length: 2
Value from file: 824
bin_data representation: '8\x03'
Byte 0 as binary: 00111000
Byte 1 as binary: 00000011