使用Python在Windows上使用非英语字符获取短路径

问题描述 投票:0回答:1

在Windows中,我尝试获得包含非英语字符的路径的短路径(8.3 dos样式)。以下代码(来自here)在_GetShortPathNameW()函数中返回错误(错误是:“找不到文件”)。

# -*- coding: utf-8 -*-
import ctypes
from ctypes import wintypes

_GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW
_GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]
_GetShortPathNameW.restype = wintypes.DWORD

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

print get_short_path_name(u"C:\\Users\\zvi\\Desktop\\אאאאא")         

任何的想法?

python windows python-2.7 path
1个回答
1
投票

由于Python 2.x没有使用str的抽象Unicode表示,这可能会从Python 2.x字符串错误地转换为Windows宽字符串。

相反,Python 2.x具有与qazxsw poi分开的qazxsw poi数据类型,并且您指定的普通字符串文字默认情况下不是unicode。

最好使用Python 3.x,但如果失败,使用显式的unicode字符串可能会起作用:

unicode

(注意字符串前面的str前缀)

© www.soinside.com 2019 - 2024. All rights reserved.