How to find name of file type in python

Question:

I’m attempting to create a clone of the windows 10 file explorer in python using tkinter and I cant work out how to get the name of the file type from its file extension like file explorer does

I have already got a function to get the programs file extension and another to open it in the default application however nowhere online has a solution to my issue

Asked By: Platinum

||

Answers:

My guess is that Microsoft uses a dictionary to do that.

I would suggest doing the same:

def get_file_type():
    extension_full_names = {".txt":"Text file", ".py":"Python file"}

    file_extension = getFileExtension(file)
    
    if file_extension in extension_full_names.keys():
       return extension_full_names[file_extension]
    
    return f"{file_extension} file" # extension not in your dictionary
Answered By: benicamera

This value is stored in the registery at the location _HKEY_LOCAL_MACHINESOFTWAREClasses. For example, the value of the key Python.File at this location is Python File.

The first step is to get the key name linked with the human readable name of the file. That key is the value of the key name as the extension name located at the same path.
Then, thanks to this value, get the name of the file by its key name.

To sum up with an example:
HKEY_LOCAL_MACHINESOFTWAREClasses.py gives Python.File
HKEY_LOCAL_MACHINESOFTWAREClassesPython.File gives Python File

In python, to get values in the registery, you can use winreg package.

from typing import Tuple
from winreg import HKEYType, ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx


class ExtensionQuery:
    def __init__(self):
        self.base: str = r"SOFTWAREClasses"
        self.reg: HKEYType = ConnectRegistry(None, HKEY_LOCAL_MACHINE)

    def _get_value_from_class(self, class_str: str) -> str:
        path: str = fr"{self.base}{class_str}"
        key: HKEYType = OpenKey(self.reg, path)
        value_tuple: Tuple[str, int] = QueryValueEx(key, "")
        return value_tuple[0]

    def get_application_name(self, ext: str) -> str:
        return self._get_value_from_class(self._get_value_from_class(ext))


query = ExtensionQuery()
print(query.get_application_name(".py"))
Answered By: Julien Sorin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.