import codecs
import logging


def file2dict(path, kn=0, vn=1, sep='\t', encoding='utf-8', ktype=None, vtype=None, skip_line=0):
    """
    build a dict from a file.
    @param path: input file path
    @param kn: the column number of key
    @param vn: the column number of value
    @param sep: the field seperator
    @param encoding: the input encoding
    @param ktype: custom a function applied to the key of each line
    @param vtype: custom a function applied to the value of each line
    @param skip_line: skip lines number
    @return: a key value dict
    """
    d = {}
    line_number = 0
    with codecs.open(path, encoding=encoding) as fp:
        for line in fp:
            if not line.strip():
                continue
            line_number += 1
            if line_number <= skip_line:
                continue
            tokens = line.rstrip('\n\r ').split(sep)
            try:
                key = tokens[kn]
                if ktype:
                    key = ktype(key)
                if vn is None:
                    value = tokens[:kn] + tokens[kn + 1:]
                else:
                    value = tokens[vn]
                if vtype:
                    value = vtype(value)
                d[key] = value
            except IndexError:
                logging.exception('invalid line: %s' % line)
    return d