如何在python中获取Windows短文件名?

Exp*_*ing 10 python python-2.7 python-3.x

我需要从我的python代码中确定Windows短文件名.为此我可以使用win32api找到解决方案.

import win32api
long_file_name='C:\Program Files\I am a file'
short_file_name=win32api.GetShortPathName(long_file_name)
Run Code Online (Sandbox Code Playgroud)

参考:http://blog.lowkster.com/2008/10/spaces-in-directory-names-i-really-love.html

不幸的是,我需要安装pywin32ActivePython在我的情况下不可能.

也参考SO:

在python中获取短路径:在python中获取短路径

ick*_*fay 14

你可以用ctypes.根据MSDN的文档,GetShortPathName是在KERNEL32.DLL.请注意,实际函数GetShortPathNameW用于w ide(Unicode)字符和GetShortPathNameA单字节字符.由于宽字符更通用,我们将使用该版本.首先,根据文档设置原型:

import ctypes
from ctypes import wintypes
_GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW
_GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]
_GetShortPathNameW.restype = wintypes.DWORD
Run Code Online (Sandbox Code Playgroud)

GetShortPathName首先在没有目标缓冲区的情况下调用它.它将返回制作目标缓冲区所需的字符数.然后使用该大小的缓冲区再次调用它.如果由于TOCTTOU问题,返回值仍然较大,请继续尝试,直到你做对了.所以:

def get_short_path_name(long_name):
    """
    Gets the short path name of a given long path.
    http://stackoverflow.com/a/23598461/200291
    """
    output_buf_size = 0
    while True:
        output_buf = ctypes.create_unicode_buffer(output_buf_size)
        needed = _GetShortPathNameW(long_name, output_buf, output_buf_size)
        if output_buf_size >= needed:
            return output_buf.value
        else:
            output_buf_size = needed
Run Code Online (Sandbox Code Playgroud)

  • 呼叫可能会失败。因此,请使用“kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)”而不是“ctypes.windll.kernel32”。然后,如果“needed == 0”,则通过“raise ctypes.WinError(ctypes.get_last_error())”引发异常。 (2认同)