如何使用Python 2标准库在Windows中检索文件的详细信息

时间:2017-04-26 19:40:57

标签: python file properties ctypes details

我需要在Windows中阅读文件的详细信息,以便我可以查询文件的文件版本'显示在“文件属性”窗口的“详细信息”选项卡中。

parseInt

我还没有找到标准库中的任何内容,这使得这很容易实现,但想想如果我能找到合适的Windows函数,我可以用ctypes完成它。

有没有人有任何示例代码,或者他们可以指向一个让我阅读此信息的Windows功能。我已经看了一眼File Properties Dialog,但据我所知,这并不是很正确。

2 个答案:

答案 0 :(得分:1)

使用Version Information functions中的win32 api ctypes。 api使用起来有点繁琐,但我也想要这样,所以将a quick script放在一起作为例子。

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

也可以用作模块,请参阅VersionInfo类。使用Python 2.7和3.6检查几个文件。

答案 1 :(得分:0)

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)