MrBubbles
MrBubbles

Reputation: 415

How can I retrieve a file's details in Windows using the Standard Library for Python 2

I need to read the details for a file in Windows so that I can interrogate the file's 'File version' as displayed in the Details tab of the File Properties window.

File Properties Dialog

I haven't found anything in the standard library that makes this very easy to accomplish but figured if I could find the right windows function, I could probably accomplish it using ctypes.

Does anyone have any exemplary code or can they point me to a Windows function that would let me read this info. I took a look a GetFileAttributes already, but that wasn't quite right as far as I could tell.

Upvotes: 3

Views: 4184

Answers (2)

gz.
gz.

Reputation: 6711

Use the win32 api Version Information functions from ctypes. The api is a little fiddly to use, but I also want this so have thrown together a quick script as an example.

usage: version_info.py [-h] [--lang LANG] [--codepage CODEPAGE] path

Can also use as a module, see the VersionInfo class. Checked with Python 2.7 and 3.6 against a few files.

Upvotes: 1

MrBubbles
MrBubbles

Reputation: 415

import array
from ctypes import *

def get_file_info(filename, info):
    """
    Extract information from a file.
    """
    # Get size needed for buffer (0 if no info)
    size = windll.version.GetFileVersionInfoSizeA(filename, None)

    # If no info in file -> empty string
    if not size:
        return ''

    # Create buffer
    res = create_string_buffer(size)
    # Load file informations into buffer res
    windll.version.GetFileVersionInfoA(filename, None, size, res)
    r = c_uint()
    l = c_uint()
    # Look for codepages
    windll.version.VerQueryValueA(res, '\\VarFileInfo\\Translation',
                              byref(r), byref(l))

    # If no codepage -> empty string
    if not l.value:
        return ''
    # Take the first codepage (what else ?)
    codepages = array.array('H', string_at(r.value, l.value))
    codepage = tuple(codepages[:2].tolist())

    # Extract information
    windll.version.VerQueryValueA(res, ('\\StringFileInfo\\%04x%04x\\'
    + info) % codepage, byref(r), byref(l))

    return string_at(r.value, l.value)

Upvotes: 0

Related Questions