Determine the file type and return it.
481320
def determine_type(filename):
    ''''''
    ftype = magic.from_file(filename, mime=True).decode('utf8')
    if ftype == 'text/plain':
        ftype = 'text'
    elif ftype == 'image/svg+xml':
        ftype = 'svg'
    else:
        ftype = ftype.split('/')[1]
    return ftype
331028
def get_file_type(filename):
    
    txt_extensions = [".txt", ".dat", ".csv"]
    hdf_extensions = [".hdf", ".h5", ".bkup", ".checkpoint"]
    for ext in hdf_extensions:
        if filename.endswith(ext):
            with _h5py.File(filename, 'r') as fp:
                filetype = fp.attrs['filetype']
            return filetypes[filetype]
    for ext in txt_extensions:
        if filename.endswith(ext):
            return InferenceTXTFile
    raise TypeError("Extension is not supported.")
569136
function getFileTypeReg(type) {
    var map = [],
        ext = ""; // fis.config.get('project.fileType.' + type);
    if (type === 'text') {
        map = TEXT_FILE_EXTS;
    } else if (type === 'image') {
        map = IMAGE_FILE_EXTS;
    } else {
        xgulp.log.error('invalid file type [%s]', type);
    }
    if (ext && ext.length) {
        if (typeof ext === 'string') {
            ext = ext.split(/\s*,\s*/);
        }
        map = map.concat(ext);
    }
    map = map.join('|');
    return new RegExp('\\.(?:' + map + ')$', 'i');
}
106803
def identify_link_type(filename):
    '''
    '''
    mime_type = mimetypes.guess_type(filename)[0]

    if not mime_type:
        return

    if mime_type == 'text/css':
        return LinkType.css
    elif mime_type == 'application/javascript':
        return LinkType.javascript
    elif mime_type == 'text/html' or mime_type.endswith('xml'):
        return LinkType.html
    elif mime_type.startswith('video') or \
            mime_type.startswith('image') or \
            mime_type.startswith('audio') or \
            mime_type.endswith('shockwave-flash'):
        return LinkType.media
609421
def _preferred_filetype(self, filetypes):
        
        if not isinstance(filetypes, list):
            filetypes = [filetypes]

        # look through the file types and use the first one that we have loaded
        for filetype in filetypes:
            if filetype in self.file_handlers:
                return filetype
        return None
714169
def isFile(self):
        
        try:
            filetype = file
        except NameError:
            filetype = io.IOBase

        return self._wrap(type(self.obj) is filetype)
1143574
def _is_text_file(filename):
    '''
    
    '''
    type_of_file = os.popen('file -bi {0}'.format(filename), 'r').read()
    return type_of_file.startswith('text')
1154735
def type(filename):
    
    assert isinstance(filename, basestring)
    while 1:
        filename, suffix = os.path.splitext (filename)
        if not suffix: return None
        suffix = suffix[1:]

        if suffix in __suffixes_to_types:
            return __suffixes_to_types[suffix]
846842
def smart_content_type(self):
        """"""
        content_type = self.content_type
        if content_type in (None, '', 'application/octet-stream'):
            content_type, _ = mimetypes.guess_type(self.name)

        return content_type
806397
def determine_file_type(self, z):
        """"""

        content = z.read('[Content_Types].xml')
        with io.BytesIO(content) as b:
            encoding = self._analyze_file(b)
            if encoding is None:
                encoding = 'utf-8'
            b.seek(0)
            text = b.read().decode(encoding)
            soup = bs4.BeautifulSoup(text, 'xml')
            for o in soup.find_all('Override'):
                name = o.attrs.get('PartName')
                for k, v in MIMEMAP.items():
                    if name.startswith('/{}/'.format(k)):
                        self.type = v
                        break
                if self.type:
                    break
        self.filepattern = DOC_PARAMS[self.type]['filepattern']
        self.namespaces = DOC_PARAMS[self.type]['namespaces']
        self.captures = sv.compile(DOC_PARAMS[self.type]['captures'], DOC_PARAMS[self.type]['namespaces'])
442819
def file_type(filename, param='rb'):
    """"""
    magic_dict = {
        b"\x1f\x8b\x08": "gz",
        b"\x42\x5a\x68": "bz2",
        b"\x50\x4b\x03\x04": "zip"
    }
    if param.startswith('w'):
        return filename.split('.')[-1]
    max_len = max(len(x) for x in magic_dict)
    with open(filename, 'rb') as f:
        file_start = f.read(max_len)
    for magic, filetype in list(magic_dict.items()):
        if file_start.startswith(magic):
            return filetype
    return "no match"
715708
def get_type(full_path):
    """"""
    status = {'type': []}
    if os.path.ismount(full_path):
        status['type'] += ['mount-point']
    elif os.path.islink(full_path):
        status['type'] += ['symlink']
    if os.path.isfile(full_path):
        status['type'] += ['file']
    elif os.path.isdir(full_path):
        status['type'] += ['dir']
    if not status['type']:
        if os.stat.S_ISSOCK(status['mode']):
            status['type'] += ['socket']
        elif os.stat.S_ISCHR(status['mode']):
            status['type'] += ['special']
        elif os.stat.S_ISBLK(status['mode']):
            status['type'] += ['block-device']
        elif os.stat.S_ISFIFO(status['mode']):
            status['type'] += ['pipe']
    if not status['type']:
        status['type'] += ['unknown']
    elif status['type'] and status['type'][-1] == 'symlink':
        status['type'] += ['broken']
    return status['type']
44200
def get_content_type(*names):
    """"""
    for name in names:
        if name is not None:
            mimetype, encoding = mimetypes.guess_type(name)
            if mimetype is not None:
                if isinstance(mimetype, bytes):
                    return mimetype.decode("ascii")
                else:
                    return mimetype
    else:
        return "application/octet-stream"
556786
def _get_content_type(self, filename):
        
        mntype = mimetypes.guess_type(filename)[0]
        filename, fileExtension = os.path.splitext(filename)
        if mntype is None and\
            fileExtension.lower() == ".csv":
            mntype = "text/csv"
        elif mntype is None and \
            fileExtension.lower() == ".sd":
            mntype = "File/sd"
        elif mntype is None:
            #mntype = 'application/octet-stream'
            mntype= "File/%s" % fileExtension.replace('.', '')
        return mntype
187459
def _get_content_type(self, file):
        
        if file.mimetype:
            return file.mimetype

        # get file extension
        _, extension = os.path.splitext(file.name)
        extension = extension.strip('.')

        # Make an educated guess about what the Content-Type should be.
        return media_types[extension] if extension in media_types else 'binary/octet-stream'
948336
def prompt_filetype(args):
    """"""
    valid_types = ('print', 'text', 'csv', 'pdf', 'html')
    if not any(args[x] for x in valid_types):
        try:
            filetype = input('Print or save output as ({0}): '
                             .format(', '.join(valid_types))).lower()
            while filetype not in valid_types:
                filetype = input('Invalid entry. Choose from ({0}): '
                                 .format(', '.join(valid_types))).lower()
        except (KeyboardInterrupt, EOFError):
            return
        args[filetype] = True
1264883
def _detect_content_type(self, filename):
        '''
        '''
        name, ext = os.path.splitext(filename)
        if not ext:
            raise MessageError('File requires an extension.')
        ext = ext.lower()
        if ext.lstrip('.') in self._banned_extensions:
            err = 'Extension "{0}" is not allowed.'
            raise MessageError(err.format(ext))
        if not mimetypes.inited:
            mimetypes.init()
        return mimetypes.types_map.get(ext, self._default_content_type)