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

15 投票
1 回答
12066 浏览
提问于 2025-04-18 06:14

我需要在我的Python代码中获取Windows的短文件名。为此,我可以使用win32api找到解决方案。

import win32api
long_file_name='C:\Program Files\I am a file'
short_file_name=win32api.GetShortPathName(long_file_name)

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

不过,遗憾的是,我需要安装pywin32ActivePython,但在我的情况下这不太可能。

还有来自Stack Overflow的参考:

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

1 个回答

23

你可以使用ctypes这个库。根据MSDN上的说明GetShortPathName这个函数是在KERNEL32.DLL里面的。需要注意的是,实际的函数有两个:GetShortPathNameW是用来处理wide(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

使用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

撰写回答