Home > OS >  How to find name of file type in python
How to find name of file type in python

Time:12-01

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

CodePudding user response:

This value is stored in the registery at the location _HKEY_LOCAL_MACHINE\SOFTWARE\Classes. For exemple, the velue 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's 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_MACHINE\SOFTWARE\Classes\.py gives Python.File \HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Python.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"SOFTWARE\Classes"
        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"))

CodePudding user response:

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
  • Related