Read the text header for each file

    Parameters
    ----------
    channel_file : Path
        path to single filename with the header

    Returns
    -------
    dict
        header
167014
def _read_header(filename):
    
    with filename.open('rb') as f:
        h = f.read(HDR_LENGTH).decode()

        header = {}
        for line in h.split('\n'):
            if '=' in line:
                key, value = line.split(' = ')
                key = key.strip()[7:]
                value = value.strip()[:-1]
                header[key] = value

    return header
501661
def _read_file(self, file):  # type: (str) -> Optional[str]
        
        if not self.setup_file_name:
            return None
        source = None
        if os.path.isfile(file):
            with self.file_opener.open_this(file, "r") as setup_py:
                source = setup_py.read()
        return source
515494
def read_file(file):
	
	if hasattr(file, "read"):
		return file.read()
	if hasattr(file, "read_bytes"):
		return file.read_bytes()
	with open(file, "rb") as f:
		return f.read()
603835
def _parse_header(lines):
    
    header_count = _extract_header_number(lines)
    header_dict = {}
    for i in range(2, header_count + 2):
        pair = _extract_header_value(lines[i])

        if not pair:  # Ignore empty strings
            continue

        header_dict.update(pair)
    return header_dict
264367
def readbdfv1(filename, bdfext='.bdf', bhfext='.bhf'):
    
    return header.readbhfv1(filename, True, bdfext, bhfext)
185811
def header_from_raw_header_data(cls, raw_header):
        
        try:
            header = MessageHeader(*cls.header_struct.unpack(raw_header))
        except struct.error:
            raise Exception("Invalid message header received")
        return header
1273291
def _readFile(self, sldir, fileName, sep):
        '''
        

        '''

        if sldir.endswith(os.sep):
            fileName = str(sldir)+str(fileName)
        else:
            fileName = str(sldir)+os.sep+str(fileName)


        fileLines=[] #list of lines in the file
        header=[]    #list of Header lines
        dataCols=[]  #Dictionary of data column names
        data=[]      #List of Data lists
        cols=[]      #List of column names

        f=open(fileName,'r')
        fileLines=f.readlines()
        i=0
        if self.datatype != 'trajectory':

            while i<len(fileLines):
                if fileLines[i].startswith(self.header_char):
                    tmp=fileLines[i].lstrip(self.header_char)
                    header.append(tmp.strip())
                else:
                    break
                i+=1

            cols=fileLines[i].split(sep)

            tmp=[]
            tmp1=[]
            for j in range(len(cols)):
                tmp1=cols[j].strip()
                if tmp1 !='':
                    tmp.append(tmp1)
            cols=tmp
            i+=1
        else:
            header={}
            while fileLines[i].startswith('#') or '=' in fileLines[i]:
                if fileLines[i].startswith('#') and cols==[]:
                    cols=fileLines[i].strip('#')
                    cols=cols.strip()
                    cols=cols.split()
                elif fileLines[i].startswith('#'):
                    tmp1=fileLines[i].strip('#')
                    tmp1=tmp1.strip()
                    self.headerLines.append(tmp1)
                elif not fileLines[i].startswith('#'):
                    tmp=fileLines[i].split('=')
                    tmp[0]=tmp[0].strip()
                    tmp[1]=tmp[1].strip()
                    if header=={}:
                        header={str(tmp[0]):str(tmp[1])}
                    else:
                        header[str(tmp[0])]=str(tmp[1])
                i+=1
        while i<len(fileLines):
            if fileLines[i].startswith('#'):
                i=i+1
            else:
                tmp=fileLines[i].split()
                for j in range(len(tmp)):
                    tmp[j]=tmp[j].strip()
                data.append(tmp)
                i+=1
        tmp=[]
        tmp1=[]
        for j in range(len(data)):
            for k in range(len(data[j])):
                tmp1=data[j][k].strip()
                if tmp1 !='':
                    tmp.append(tmp1)
            data[j]=tmp
            tmp=[]
        tmp=[]

        for j in range(len(cols)):
            for k in range(len(data)):
                try:
                    a=float(data[k][j])
                    tmp.append(a)
                except ValueError:
                    tmp.append(data[k][j])
                #else:
                 #   tmp.append(float(data[k][j])) # previously tmp.append(float(data[k][j]))
            tmp=array(tmp)

            if j == 0:
                dataCols={cols[j]:tmp}
            else:
                dataCols[cols[j]]=tmp
            tmp=[]

        return header,dataCols
1259769
def header(args):
    
    from jcvi.formats.base import DictFile

    p = OptionParser(header.__doc__)
    p.add_option("--prefix", default="",
                 help="Prepend text to line number [default: %default]")
    p.add_option("--ids", help="Write ids to file [default: %default]")
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    mstmap, conversion_table = args
    data = MSTMap(mstmap)
    hd = data.header
    conversion = DictFile(conversion_table)
    newhd = [opts.prefix + conversion.get(x, x) for x in hd]

    print("\t".join(hd))
    print("--->")
    print("\t".join(newhd))

    ids = opts.ids
    if ids:
        fw = open(ids, "w")
        print("\n".join(newhd), file=fw)
        fw.close()
1319747
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
        
        # Set file extension property
        self.fileExtension = extension

        # Dictionary of keywords/cards and parse function names
        KEYWORDS = {'ALPHA': cic.cardChunk,
                    'BETA': cic.cardChunk,
                    'THETA': cic.cardChunk,
                    'LINKS': cic.cardChunk,
                    'MAXNODES': cic.cardChunk,
                    'CONNECT': cic.connectChunk,
                    'LINK': cic.linkChunk}

        links = []
        connectivity = []

        # Parse file into chunks associated with keywords/cards
        with open(path, 'r') as f:
            chunks = pt.chunk(KEYWORDS, f)

        # Parse chunks associated with each key
        for key, chunkList in iteritems(chunks):
            # Parse each chunk in the chunk list
            for chunk in chunkList:
                # Call chunk specific parsers for each chunk
                result = KEYWORDS[key](key, chunk)

                # Cases
                if key == 'LINK':
                    # Link handler
                    links.append(self._createLink(result, replaceParamFile))

                elif key == 'CONNECT':
                    # Connectivity handler
                    connectivity.append(result)

                else:
                    # Global variable handler
                    card = result['card']
                    value = result['values'][0]
                    # Cases
                    if card == 'LINKS':
                        self.links = int(value)
                    elif card == 'MAXNODES':
                        self.maxNodes = int(value)
                    elif card == 'ALPHA':
                        self.alpha = float(vrp(value, replaceParamFile))
                    elif card == 'BETA':
                        self.beta = float(vrp(value, replaceParamFile))
                    elif card == 'THETA':
                        self.theta = float(vrp(value, replaceParamFile))

        self._createConnectivity(linkList=links, connectList=connectivity)

        if spatial:
            self._createGeometry(session, spatialReferenceID)
452628
def read_header(cls, headers_path, block_height, allow_none=False):
        
        if os.path.exists(headers_path):
    
            header_parser = BlockHeaderSerializer()
            sb = os.stat( headers_path )
            if sb.st_size < BLOCK_HEADER_SIZE * block_height:
                # beyond EOF 
                if allow_none:
                    return None 
                else:
                    raise Exception('EOF on block headers')

            with open( headers_path, "rb" ) as f:
                f.seek( block_height * BLOCK_HEADER_SIZE, os.SEEK_SET )
                hdr = SPVClient.read_header_at( f )

            return hdr
        else:
            if allow_none:
                return None
            else:
                raise Exception('No such file or directory: {}'.format(headers_path))
19594
def read_from_file(file_name):
    
    from .docxfile import DOCXFile

    dfile = DOCXFile(file_name)
    dfile.parse()

    return dfile
355752
def _read_file_data(self, message_name_filter_list, read_until=None):
        

        if read_until is None:
            read_until = 1 << 50 # make it larger than any possible log file

        try:
            # pre-init reusable objects
            header = self._MessageHeader()
            msg_data = self._MessageData()

            while True:
                data = self._file_handle.read(3)
                header.initialize(data)
                data = self._file_handle.read(header.msg_size)
                if len(data) < header.msg_size:
                    break # less data than expected. File is most likely cut

                if self._file_handle.tell() > read_until:
                    if self._debug:
                        print('read until offset=%i done, current pos=%i' %
                              (read_until, self._file_handle.tell()))
                    break

                if header.msg_type == self.MSG_TYPE_INFO:
                    msg_info = self._MessageInfo(data, header)
                    self._msg_info_dict[msg_info.key] = msg_info.value
                elif header.msg_type == self.MSG_TYPE_INFO_MULTIPLE:
                    msg_info = self._MessageInfo(data, header, is_info_multiple=True)
                    self._add_message_info_multiple(msg_info)
                elif header.msg_type == self.MSG_TYPE_PARAMETER:
                    msg_info = self._MessageInfo(data, header)
                    self._changed_parameters.append((self._last_timestamp,
                                                     msg_info.key, msg_info.value))
                elif header.msg_type == self.MSG_TYPE_ADD_LOGGED_MSG:
                    msg_add_logged = self._MessageAddLogged(data, header,
                                                            self._message_formats)
                    if (message_name_filter_list is None or
                            msg_add_logged.message_name in message_name_filter_list):
                        self._subscriptions[msg_add_logged.msg_id] = msg_add_logged
                    else:
                        self._filtered_message_ids.add(msg_add_logged.msg_id)
                elif header.msg_type == self.MSG_TYPE_LOGGING:
                    msg_logging = self.MessageLogging(data, header)
                    self._logged_messages.append(msg_logging)
                elif header.msg_type == self.MSG_TYPE_DATA:
                    msg_data.initialize(data, header, self._subscriptions, self)
                    if msg_data.timestamp != 0 and msg_data.timestamp > self._last_timestamp:
                        self._last_timestamp = msg_data.timestamp
                elif header.msg_type == self.MSG_TYPE_DROPOUT:
                    msg_dropout = self.MessageDropout(data, header,
                                                      self._last_timestamp)
                    self._dropouts.append(msg_dropout)
                else:
                    if self._debug:
                        print('_read_file_data: unknown message type: %i (%s)' %
                              (header.msg_type, chr(header.msg_type)))
                        file_position = self._file_handle.tell()
                        print('file position: %i (0x%x) msg size: %i' % (
                            file_position, file_position, header.msg_size))

                    if self._check_file_corruption(header):
                        # seek back to advance only by a single byte instead of
                        # skipping the message
                        self._file_handle.seek(-2-header.msg_size, 1)

        except struct.error:
            pass #we read past the end of the file

        # convert into final representation
        while self._subscriptions:
            _, value = self._subscriptions.popitem()
            if len(value.buffer) > 0: # only add if we have data
                data_item = ULog.Data(value)
                self._data_list.append(data_item)
562162
def filename_from_headers(headers):
    
    if type(headers) == str:
        headers = headers.splitlines()
    if type(headers) == list:
        headers = dict([x.split(':', 1) for x in headers])
    cdisp = headers.get("Content-Disposition")
    if not cdisp:
        return None
    cdtype = cdisp.split(';')
    if len(cdtype) == 1:
        return None
    if cdtype[0].strip().lower() not in ('inline', 'attachment'):
        return None
    # several filename params is illegal, but just in case
    fnames = [x for x in cdtype[1:] if x.strip().startswith('filename=')]
    if len(fnames) > 1:
        return None
    name = fnames[0].split('=')[1].strip(' \t"')
    name = os.path.basename(name)
    if not name:
        return None
    return name
891821
def _read_etc(etc_file):
    
    etc_type = dtype([('offset', '<i'),
                      ('samplestamp', '<i'),
                      ('sample_num', '<i'),
                      ('sample_span', '<h'),
                      ('unknown', '<h')])

    with etc_file.open('rb') as f:
        f.seek(352)  # end of header
        etc = fromfile(f, dtype=etc_type)

    return etc
717705
def _ReadFileHeader(self, file_object):
    
    data_type_map = self._GetDataTypeMap('keychain_file_header')

    file_header, _ = self._ReadStructureFromFileObject(
        file_object, 0, data_type_map)

    if file_header.signature != self._FILE_SIGNATURE:
      raise errors.ParseError('Unsupported file signature.')

    if (file_header.major_format_version != self._MAJOR_VERSION or
        file_header.minor_format_version != self._MINOR_VERSION):
      raise errors.ParseError('Unsupported format version: {0:s}.{1:s}'.format(
          file_header.major_format_version, file_header.minor_format_version))

    return file_header
398390
def process_headers(data, filename):
    """"""
    headers = []
    if 'toc' in data:
        for element in PyQuery(data['toc'])('a'):
            headers.append(recurse_while_none(element))
        if None in headers:
            log.info('Unable to index file headers for: %s', filename)
    return headers
637282
def _ParseFileHeader(self, file_object):
    
    file_header_map = self._GetDataTypeMap(
        'chrome_cache_data_block_file_header')

    try:
      file_header, _ = self._ReadStructureFromFileObject(
          file_object, 0, file_header_map)
    except (ValueError, errors.ParseError) as exception:
      raise errors.ParseError(
          'Unable to parse data block file header with error: {0!s}'.format(
              exception))

    if file_header.signature != self._FILE_SIGNATURE:
      raise errors.ParseError('Unsupported data block file signature')

    format_version = '{0:d}.{1:d}'.format(
        file_header.major_version, file_header.minor_version)
    if format_version not in ('2.0', '2.1'):
      raise errors.ParseError(
          'Unsupported data block file format version: {0:s}'.format(
              format_version))

    if file_header.block_size not in (256, 1024, 4096):
      raise errors.ParseError(
          'Unsupported data block file block size: {0:d}'.format(
              file_header.block_size))