我需要知道Python中“word”所占用的字节数。我需要这个信息是因为我需要从文件中读取指定数量的单词;如果我知道一个单词占用的字节数,我就可以使用 file.read(num_bytes)
函数来从文件中读取适当数量的单词。
如何确定一个单词占用的字节数?
我需要知道Python中“word”所占用的字节数。我需要这个信息是因为我需要从文件中读取指定数量的单词;如果我知道一个单词占用的字节数,我就可以使用 file.read(num_bytes)
函数来从文件中读取适当数量的单词。
如何确定一个单词占用的字节数?
platform.architecture
函数:>>> import platform
>>> platform.architecture()
('64bit', '')
请记住,这是Python解释器编译时的字长。如果Python以32位模式编译,则在64位主机上可能会得到32的值。Note On Mac OS X (and perhaps other platforms), executable files may be universal files containing multiple architectures. To get at the “64-bitness” of the current interpreter, it is more reliable to query the sys.maxsize attribute:
is_64bits = sys.maxsize > 2**32
>>> p.architecture('/path/to/executable')
('32bit', '')
Python 中没有“单词”这个概念,当你从文件中读取二进制数据时,可以明确指定每次应该读取多少字节。
在编译器和/或平台方面,“WORD”通常确定基本数据单元的大小。而 Python 是独立于这种东西的 :)
对于“字(word)”的定义并没有一个确切的标准;除了某些体系结构将一些字节称为“字”(例如x86将2个字节称为一个字,PPC将4个字节称为一个字),但是除了这个任意值之外,并没有太多的意义。
也许最简单的解决方案是使用struct
模块;例如,格式'h'
表示有符号短整型(与英特尔“字”的定义相当)。因此,您可以这样做:
>>> import struct
>>> f = file('.vimrc')
>>> struct.unpack('h', f.read(struct.calcsize('h')))
(8226,)
>>>
这样怎么样:
def machine_word_size():
import sys
num_bytes = 0
maxint = sys.maxint
while maxint > 0:
maxint = maxint >> 8
num_bytes += 1
return num_bytes