zvi
zvi

Reputation: 4696

Get short path with non-English chars on Windows with Python

In windows, I try to get short path (8.3 dos style) of path that contains non-English chars. The following code (from here) return error in the _GetShortPathNameW() function (error is: "file not found").

# -*- 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\\אאאאא")         

Any idea?

Upvotes: 0

Views: 318

Answers (1)

blubberdiblub
blubberdiblub

Reputation: 4135

This will likely convert incorrectly from a Python 2.x string to a Windows wide string due to Python 2.x not using abstract Unicode representation for str.

Instead, Python 2.x has a unicode datatype separate from str and plain string literals you specify are not unicode by default.

It would probably be best to use Python 3.x, but failing that, using an explicit unicode string might work:

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

(note the u prefix in front of the string)

Upvotes: 1

Related Questions