我需要从我的 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 http://blog.lowkster.com/2008/10/spaces-in-directory-names-i-really-love.html
不幸的是我需要安装pywin32
or ActivePython
这对我来说是不可能的。
还参考了SO:
在Python中获取短路径:在python中获取短路径 https://stackoverflow.com/questions/6085688/getting-short-path-in-python
您可以使用ctypes https://docs.python.org/3/library/ctypes.html。根据MSDN 上的文档 http://msdn.microsoft.com/en-us/library/aa364989.aspx, GetShortPathName
is in KERNEL32.DLL
。请注意,实际函数是GetShortPathNameW
for 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 https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use问题,返回值还是比较大,继续尝试,直到做对为止。所以:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)