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

问题描述:

我需要在Windows中读取文件的详细信息,以便可以查询文件的详细信息选项卡中显示的文件的“文件版本”属性窗口。如何在Windows中使用Python 2的标准库检索文件的详细信息

File Properties Dialog

我还没有发现在标准库中任何让这很容易做到,但想如果我能找到合适的窗口功能,我可以使用ctypes的可能完成它。

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

+0

是否这样:http://*.com/questions/12521525/reading-metadata-with-python帮助你? – thebjorn

使用win32 api Version Information functionsctypes。这个api有点用处不大,但我也想这样把它们扔在一起a quick script为例。

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

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

+0

明白了。感谢您指点我正确的方向。 – MrBubbles

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)