file1 = open("test.txt", 'wb')
file1.write(struct.pack('icic', 1, '\t', 2, '\n'))
file1.close()
print os.path.getsize("test.txt")
它给了我 13。但我认为它应该是 4 + 1 + 4 + 1 = 10 个字节。似乎它存储 1 个字节的 '\n',但存储 4 个字节的 '\t'。和想法? 谢谢!
最佳答案
要获取实际的结构大小,请使用 struct.calcsize()
:
>>> import struct
>>> struct.calcsize('icic')
13
那是因为您使用的是默认对齐方式,然后应用了 C 规则:
By default, C types are represented in the machine’s native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler).
第一个 ic
将只有 5 个字节,但如果你列出它两次,C 会将其填充为 8 个,因此下一个 ic
对将其变为 13 个。如果您使用 3 个 ic
对,您将得到 21 个,依此类推。C 填充 i
整数以与 4 字节组对齐。这data structure alignment用于提高内存性能,但在尝试将其用于不同目的时可能会出乎意料。
改为选择明确的字节顺序:
>>> struct.calcsize('>icic')
10
关于python - 为什么我在 python 中得到 4 个字节的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24859868/