2011-02-05 89 views
2

我有一个储存在含有ASCII文本标题,以空字符结尾的文件有些成像数据,其次是二进制数据。 ascii标题的长度各不相同,我想知道什么是打开文件,读取标题并找到空字符,然后加载二进制数据(以Python)的最佳方式。如何在ASCII头后的二进制数据读取在Python

感谢您的帮助,
詹姆斯

+1

你看过http://docs.python.org/library/struct.html模块了吗? – 2011-02-05 00:14:57

+0

除了结构模块,如果有均匀的大的块(即,相同的类型,32位浮点,16位的uint等)数据看看阵列模块:http://docs.python.org /library/array.html或者,如果碰巧你会使用numpy,numpy.fromfile对于这类事情非常有用。 – 2011-02-05 00:32:02

回答

1

请问像这样的工作:

with open('some_file','rb') as f: 
    binary_data = f.read().split('\0',1)[1] 
1

或许应该开始像这样的东西。

with open('some file','rb') as input: 
    aByte= input.read(1) 
    while aByte and ord(aByte) != 0: aByte= input.read(1) 
    # At this point, what's left is the binary data. 

Python版本号码对于这类事情很重要。这个问题是read函数的结果。一些版本可以返回字节(数字)。其他版本将返回字符串(这需要ord(aByte))。

0

其他人已经回答了你的方向问题,但我想我会添加此。

当处理二进制数据,我常常觉得有用的子类file和添加各种说服方法用于读取/写入打包二进制数据。

这是矫枉过正简单的事情,但如果你发现自己分析大量的二进制文件格式,这是值得额外的努力以避免重复自己。

如果不出意外,希望它作为如何使用struct一个有用的例子。在一个侧面说明,这是从旧代码拉,并且是非常多很多python 2.x. Python 3.x处理这个(特别是字符串与字节)显着不同。

import struct 
import array 

class BinaryFile(file): 
    """ 
    Automatically packs or unpacks binary data according to a format 
    when reading or writing. 
    """ 
    def __init__(self, *args, **kwargs): 
     """ 
     Initialization is the same as a normal file object 
     %s""" % file.__doc__ 
     super(BinaryFile, self).__init__(self, *args, **kwargs) 

    def read_binary(self,fmt): 
     """ 
     Read and unpack a binary value from the file based 
     on string fmt (see the struct module for details). 
     This will strip any trailing null characters if a string format is 
     specified. 
     """ 
     size = struct.calcsize(fmt) 
     data = self.read(size) 
     # Reading beyond the end of the file just returns '' 
     if len(data) != size: 
      raise EOFError('End of file reached') 
     data = struct.unpack(fmt, data) 

     for item in data: 
      # Strip trailing zeros in strings 
      if isinstance(item, str): 
       item = item.strip('\x00') 

     # Unpack the tuple if it only has one value 
     if len(data) == 1: 
      data = data[0] 

     return data 

    def write_binary(self, fmt, dat): 
     """Pack and write data to the file according to string fmt.""" 
     # Try expanding input arguments (struct.pack won't take a tuple) 
     try: 
      dat = struct.pack(fmt, *dat) 
     except (TypeError, struct.error): 
      # If it's not a sequence (TypeError), or if it's a 
      # string (struct.error), don't expand. 
      dat = struct.pack(fmt, dat) 
     self.write(dat) 

    def read_header(self, header): 
     """ 
     Reads a defined structure "header" consisting of a sequence of (name, 
     format) strings from the file. Returns a dict with keys of the given 
     names and values unpaced according to the given format for each item in 
     "header". 
     """ 
     header_values = {} 
     for key, format in header: 
      header_values[key] = self.read_binary(format) 
     return header_values 

    def read_nullstring(self): 
     """ 
     Reads a null-terminated string from the file. This is not implemented 
     in an efficient manner for long strings! 
     """ 
     output_string = '' 
     char = self.read(1) 
     while char != '\x00': 
      output_string += char 
      char = self.read(1) 
      if len(char) == 0: 
       break 
     return output_string 

    def read_array(self, type, number): 
     """ 
     Read data from the file and return an array.array of the given 
     "type" with "number" elements 
     """ 
     size = struct.calcsize(type) 
     data = self.read(size * number) 
     return array.array(type, data)