How to get file’s properties from Windows’ registry?

I’m trying to get a file type with Python. For example, if I give the code “somearchive.rar” it must return “WinRAR Archive”. If I give it “someapplication.exe” it must return “Application”, etc…

Basically the text you see when you open a file’s properties in Windows, on the “File type” line.

I don’t know how to do this, though I think you can do it by looking at the registry or something similar and taking the file’s properties (or file’s extension properties?) and then keeping only the type, because I saw this code

def def_app(estensione):
    class_root = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, estensione)
    with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'{}shellopencommand'.format(class_root)) as key:
        command = winreg.QueryValueEx(key, '')[0]
        return shlex.split(command)[0]

that looks at the registry and gives you the default application that opens files with the given extension.


OK, so I found out how to do it… This code checks the file type (or association) by looking in the Windows’ registry (the same as opening regedit, going in HKEY_CLASSES_ROOT and then looking at the keys in there, as the user @martineau suggested):

rawcom = os.popen("assoc ."+command[len(command)-1]).read().split("=")

It is already split, so I can do rawcom[1] and get the file type easily. If there isn’t a file association in the Windows’ registry, it checks the file type using this code that I found:

def get_file_metadata(path, filename, metadata):
    sh = win32com.client.gencache.EnsureDispatch('Shell.Application', 0)
    ns = sh.NameSpace(path)
    file_metadata = dict()
    item = ns.ParseName(str(filename))
    for ind, attribute in enumerate(metadata):
        attr_value = ns.GetDetailsOf(item, ind)
        if attr_value:
            file_metadata[attribute] = attr_value
    return file_metadata

if __name__ == '__main__':
    folder = direc
    filename = file
    metadata = ['Name', 'Size', 'Item type', 'Date modified', 'Date created']
    proprietà = get_file_metadata(folder, filename, metadata)

It does exactly what I was trying to do at the start, getting the file type as if I was opening the file’s properties in the Windows explorer. With this I put the file metadata in a dictionary and then get only the “Item type” value.