Python get file extension

40 Python code examples are found related to " get file extension". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: misc.py    From sureal with Apache License 2.0 6 votes vote down vote up
def get_file_name_without_extension(path):
    """

    >>> get_file_name_without_extension('yuv/src01_hrc01.yuv')
    'src01_hrc01'
    >>> get_file_name_without_extension('yuv/src01_hrc01')
    'src01_hrc01'
    >>> get_file_name_without_extension('abc/xyz/src01_hrc01.yuv')
    'src01_hrc01'
    >>> get_file_name_without_extension('abc/xyz/src01_hrc01.sdr.yuv')
    'src01_hrc01.sdr'
    >>> get_file_name_without_extension('abc/xyz/src01_hrc01.sdr.dvi.yuv')
    'src01_hrc01.sdr.dvi'

    """
    return os.path.splitext(path.split("/")[-1])[0] 
Example 2
Source File: fields.py    From drf-extra-fields with Apache License 2.0 6 votes vote down vote up
def get_file_extension(self, filename, decoded_file):
        try:
            from PIL import Image
        except ImportError:
            raise ImportError("Pillow is not installed.")
        extension = imghdr.what(filename, decoded_file)

        # Try with PIL as fallback if format not detected due
        # to bug in imghdr https://bugs.python.org/issue16512
        if extension is None:
            try:
                image = Image.open(io.BytesIO(decoded_file))
            except (OSError, IOError):
                raise ValidationError(self.INVALID_FILE_MESSAGE)

            extension = image.format.lower()

        extension = "jpg" if extension == "jpeg" else extension
        return extension 
Example 3
Source File: helper.py    From SelfTarget with MIT License 5 votes vote down vote up
def get_file_name_without_extension(filename: str) -> str:
    EXTENSIONS = [".txt"]
    basename = os.path.basename(filename)
    for ext in EXTENSIONS:
        if basename.endswith(ext):
            return os.path.splitext(basename)[0]
    return basename 
Example 4
Source File: generate_database_csv.py    From TableTrainNet with MIT License 5 votes vote down vote up
def get_file_list_per_extension(path, ext):
    """
    Returns the folder and the list of the files with the 'ext' extension in the 'path' folder
    :param path:
    :param ext:
    :return: path list
    """
    ext_list = []
    for (gen_path, file_paths, file_names) in os.walk(path):
        for file in file_names:
            if file.endswith(ext):
                ext_list.append(file)
        return gen_path, ext_list 
Example 5
Source File: pathsutils.py    From BlackSheep with MIT License 5 votes vote down vote up
def get_file_extension_from_name(name: str) -> str:
    if not name:
        return ''

    extension = pathlib.Path(name).suffix
    return extension.lower() 
Example 6
Source File: flask_cloudy.py    From flask-cloudy with MIT License 5 votes vote down vote up
def get_file_extension(filename):
    """
    Return a file extension
    :param filename:
    :return: str
    """
    return os.path.splitext(filename)[1][1:].lower() 
Example 7
Source File: flask_cloudy.py    From flask-cloudy with MIT License 5 votes vote down vote up
def get_file_extension_type(filename):
    """
    Return the group associated to the file
    :param filename:
    :return: str
    """
    ext = get_file_extension(filename)
    if ext:
        for name, group in EXTENSIONS.items():
            if ext in group:
                return name
    return "OTHER" 
Example 8
Source File: CrashAnalysisConfig.py    From afl-crash-analyzer with GNU General Public License v3.0 5 votes vote down vote up
def get_gdb_exploitable_file_extension(self):
        #I guess there is no point in running the "exploitable" gdb plugin over an ASAN binary
        if self.target_binary_plain:
            return "-"+os.path.basename(self.target_binary_plain)+self.output_prefix_plain+self.gdb_prefix+self.run_extension
        else:
            return "-"+os.path.basename(self.target_binary_instrumented)+self.output_prefix_instrumented+self.gdb_prefix+self.run_extension 
Example 9
Source File: wsfaker.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def get_file_extension():
        """
        Get a random file extension.
        :return: A random file extension.
        """
        return faker.file_extension() 
Example 10
Source File: protocols.py    From bionic with Apache License 2.0 5 votes vote down vote up
def get_fixed_file_extension(self):
        """
        Returns a file extension identifying this protocol. This value will be appended
        to the name of any file written by the protocol, and may be used to determine
        whether a file can be read by the protocol.

        This string should be unique, not shared with any other protocol. By
        convention, it doesn't include an initial period, but may include periods in
        the middle.  (For example, `"csv"`, and `"csv.zip"` would both be sensible
        file extensions.)

        If a protocol uses different file extensions for different input values, it
        should implement ``file_extension_for_value`` instead.
        """
        raise NotImplementedError() 
Example 11
Source File: common.py    From fdroidserver with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_file_extension(filename):
    """get the normalized file extension, can be blank string but never None"""
    if isinstance(filename, bytes):
        filename = filename.decode('utf-8')
    return os.path.splitext(filename)[1].lower()[1:] 
Example 12
Source File: misc.py    From sureal with Apache License 2.0 5 votes vote down vote up
def get_file_name_extension(path):
    '''
    >>> get_file_name_extension("file:///mnt/zli/test.txt")
    'txt'
    >>> get_file_name_extension("test.txt")
    'txt'
    >>> get_file_name_extension("abc")
    'abc'
    '''
    return path.split('.')[-1] 
Example 13
Source File: __init__.py    From repostat with GNU General Public License v3.0 5 votes vote down vote up
def get_file_extension(filepath: str):
    assert filepath
    filename = os.path.basename(filepath)
    basename_parts = filename.split('.')
    if len(basename_parts) == 1:
        # 'folder/filename'-case
        return filename
    elif len(basename_parts) == 2 and not basename_parts[0]:
        # 'folder/.filename'-case
        return filename
    else:
        # "normal" case
        return basename_parts[-1] 
Example 14
Source File: fileUtils.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def getFileExtension(filename):
    ext_pos = filename.rfind('.')
    if ext_pos != -1:
        return filename[ext_pos+1:]
    else:
        return '' 
Example 15
Source File: formats.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_file_extension(format_):
    """Format identifier -> file extension"""
    if format_ not in FORMAT_IDENTIFIER_TO_FORMAT_CLASS:
        raise UnknownFormatIdentifierError(format_)

    for ext, f in FILE_EXTENSION_TO_FORMAT_IDENTIFIER.items():
        if f == format_:
            return ext

    raise RuntimeError("No file extension for format %r" % format_) 
Example 16
Source File: itemtree.py    From gimp-plugin-export-layers with GNU General Public License v3.0 5 votes vote down vote up
def get_file_extension(self):
    """
    Get file extension from the `name` attribute, in lowercase. If `name` has no
    file extension, return an empty string.
    """
    return pgpath.get_file_extension(self.name) 
Example 17
Source File: itemtree.py    From gimp-plugin-export-layers with GNU General Public License v3.0 5 votes vote down vote up
def get_file_extension_from_orig_name(self):
    """
    Get file extension from the `orig_name` attribute, in lowercase. If
    `orig_name` has no file extension, return an empty string.
    """
    return pgpath.get_file_extension(self.orig_name) 
Example 18
Source File: fileext.py    From gimp-plugin-export-layers with GNU General Public License v3.0 5 votes vote down vote up
def get_filename_with_new_file_extension(
      filename, file_extension, keep_extra_trailing_periods=False):
  """
  Return a new filename with the specified new file extension.
  
  To remove the file extension from `filename`, pass an empty string, `None`, or
  a period (".").
  
  If `keep_extra_trailing_periods` is `True`, do not remove duplicate periods
  before the file extension.
  """
  filename_extension = get_file_extension(filename)
  
  if filename_extension:
    filename_without_extension = filename[0:len(filename) - len(filename_extension) - 1]
  else:
    filename_without_extension = filename
    if filename_without_extension.endswith(".") and not keep_extra_trailing_periods:
      filename_without_extension = filename_without_extension.rstrip(".")
  
  if file_extension and file_extension.startswith("."):
    file_extension = file_extension.lstrip(".")
  
  if file_extension:
    file_extension = file_extension.lower()
    new_filename = ".".join((filename_without_extension, file_extension))
  else:
    new_filename = filename_without_extension
  
  return new_filename 
Example 19
Source File: controller_view_toggle.py    From sublimetext-cfml with MIT License 5 votes vote down vote up
def get_file_extension(type):
    if type == "view":
        return ".cfm"
    if type == "controller":
        return ".cfc"
    return None 
Example 20
Source File: fs.py    From uniconvertor with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_file_extension(path):
    """
    Returns file extension without comma.
    """
    ext = os.path.splitext(path)[1]
    ext = ext.lower().replace('.', '')
    return ext 
Example 21
Source File: utilities.py    From Artemis with GNU General Public License v3.0 5 votes vote down vote up
def get_file_extension(file):
    """Return the extension of a file. Return None if there is not such property."""
    components = file.split('.')
    if len(components) > 1:
        return components[-1]
    return None 
Example 22
Source File: ls.py    From stash with MIT License 5 votes vote down vote up
def get_file_extension(path):
    """returns the file extension of path"""
    if "." not in path:
        return ""
    else:
        return path.split(".")[-1].lower() 
Example 23
Source File: __init__.py    From snapy with MIT License 5 votes vote down vote up
def get_file_extension(media_type):
    if media_type in (MEDIA_VIDEO, MEDIA_VIDEO_NOAUDIO):
        return 'mp4'
    if media_type == MEDIA_IMAGE:
        return 'jpg'
    return '' 
Example 24
Source File: models.py    From tom_base with GNU General Public License v3.0 5 votes vote down vote up
def get_file_extension(self):
        """
        Returns the extension of the file associated with this data product

        :returns: File extension
        :rtype: str
        """
        return os.path.splitext(self.data.name)[1] 
Example 25
Source File: dax_settings.py    From dax with MIT License 5 votes vote down vote up
def get_job_extension_file(self):
        """Get the job_extension_file value from the cluster section.

        :return: String of the job_extension_file value, None if empty
        """
        return self.get('cluster', 'job_extension_file') 
Example 26
Source File: __init__.py    From AdultScraperX.bundle with GNU General Public License v3.0 5 votes vote down vote up
def getMediaLocalFileExtensionName(self, media):
        '''
        获得本地媒体后缀名
        '''
        extensionname = ''
        mediafilepathlist = media.items[0].parts[0].file.split('/')
        for i in range(len(mediafilepathlist)):
            if i == (len(mediafilepathlist) - 1):
                extensionname = mediafilepathlist[i].split('0')[1]

        return extensionname 
Example 27
Source File: FileGenerator.py    From catbuffer-generators with MIT License 5 votes vote down vote up
def get_main_file_extension(self):
        """

        :return: the extension of the generated files. Example: '.java'
        """
        raise NotImplementedError('get_main_file_extension must be defined in subclass') 
Example 28
Source File: BakeLab_1_2.py    From Bakelab-Blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def get_file_extension(self,format):
        extension = ''
        if format == 'PNG':
            extension = '.png'
        if format == 'JPEG':
            extension = '.jpg'
        if format == 'TARGA':
            extension = '.tar'
        if format == 'TIFF':
            extension = '.tiff'
        if format == 'BMP':
            extension = '.bmp'
        return extension 
Example 29
Source File: compat_string.py    From pfp with MIT License 5 votes vote down vote up
def FileNameGetExtension(params, ctxt, scope, stream, coord):
    raise NotImplementedError()


# wchar_t[] FileNameGetExtensionW( const wchar_t path[] ) 
Example 30
Source File: web_utils.py    From MMFinder with MIT License 5 votes vote down vote up
def get_file_extension(filename):
    if "." not in filename:
        return ""

    return filename.rsplit('.', 1)[1].lower() 
Example 31
Source File: layer.py    From qfieldsync with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_file_extension_group(filename):
    """
    Return the basename and an extension group (if applicable)

    Examples:
         airports.shp -> 'airport', ['.shp', '.shx', '.dbf', '.sbx', '.sbn', '.shp.xml']
         forests.gpkg -> 'forests', ['.gpkg']
    """
    for group in file_extension_groups:
        for extension in group:
            if filename.endswith(extension):
                return filename[:-len(extension)], group
    basename, ext = os.path.splitext(filename)
    return basename, [ext] 
Example 32
Source File: arc_tool.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def get_file_extension(layer):
    """Try to get the file extension using arcpy.Describe
    except throws an IOError for gdbs with full filepaths"""

    try:
        file_extension = arcpy.Describe(layer).extension
    except IOError:
        file_extension = ''

    return file_extension 
Example 33
Source File: tasks.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_file_extension(file_name: str, file_path: str) -> Tuple[str, str]:
        """
        Get file extension and determine file type. Any `text/plain` file is considered to have extension `.txt`.
        :param file_name: file name + extension
        :param file_path: full file path
        :return: (extension, type_string,), type_string: 'CONTENT' or 'ARCHIVE'
        """
        _fn, ext = os.path.splitext(file_name)
        if not ext:
            known_extensions = {'text/plain': 'txt'}
            mt = python_magic.from_file(file_path)
            ext = known_extensions.get(mt) or mimetypes.guess_extension(mt)
        ext = ext or ''
        file_content = 'ARCHIVE' if ArchiveFile.check_file_is_archive(file_path, ext) else 'CONTENT'
        return ext, file_content 
Example 34
Source File: executor.py    From kafka-shell with Apache License 2.0 5 votes vote down vote up
def get_file_extension(self):
        try:
            return self.settings.get_cluster_details()["command_file_extension"]
        except KeyError:
            return None 
Example 35
Source File: filemanager.py    From script.artwork.beef with MIT License 5 votes vote down vote up
def get_file_extension(contenttype, request_url, re_search=re.compile(r'\.\w*$')):
    if contenttype in typemap:
        return typemap[contenttype]
    if re.search(re_search, request_url):
        return request_url.rsplit('.', 1)[1] 
Example 36
Source File: utils.py    From preprocessor with GNU General Public License v3.0 5 votes vote down vote up
def get_file_extension(file_path):
    """
    Returns extension for a given file path.
    :param file_path: Absolute path for the file.
    :return: file extension
    :rtype: str
    """
    components = list(filter(None, path.splitext(file_path)))
    if len(components) == 1 and not components[0].startswith("."):
        return None

    return components[-1] if len(components) > 0 else None 
Example 37
Source File: image_utils_backend.py    From nnabla with Apache License 2.0 5 votes vote down vote up
def get_file_extension(path):
        ext = ''
        file_signature = {
            '.bmp': ['424d'],
            '.dib': ['424d'],
            '.pgm': ['50350a'],
            '.jpeg': ['ffd8ffe0'],
            '.jpg': ['ffd8ffe0'],
            '.png': ['89504e470d0a1a0a'],
            '.tif': ['492049'],
            '.tiff': ['492049'],
            '.eps': ['c5d0d3c6'],
            '.gif': ['474946383761', '474946383961'],
            '.ico': ['00000100'],
        }
        if hasattr(path, "read"):
            if hasattr(path, "name"):
                ext = os.path.splitext(path.name)[1].lower()
            else:
                data = binascii.hexlify(path.read()).decode('utf-8')
                path.seek(0)
                for extension, signature in file_signature.items():
                    for s in signature:
                        if data.startswith(s):
                            ext = extension
        elif isinstance(path, str):
            ext = os.path.splitext(path)[1].lower()
        return ext 
Example 38
Source File: misc.py    From sureal with Apache License 2.0 5 votes vote down vote up
def get_file_name_with_extension(path):
    """

    >>> get_file_name_with_extension('yuv/src01_hrc01.yuv')
    'src01_hrc01.yuv'
    >>> get_file_name_with_extension('src01_hrc01.yuv')
    'src01_hrc01.yuv'
    >>> get_file_name_with_extension('abc/xyz/src01_hrc01.yuv')
    'src01_hrc01.yuv'

    """
    return path.split("/")[-1] 
Example 39
Source File: fs.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_file_extension(filename):
    """
    Return extension of given file name in lower case.
    """
    return filename.split(".")[-1].lower()