pythonwindowsctypes

How can I get the name of a drive in python


I have a list of valid drive letters, and I want to present a choice to the end user. I'd like to show them the names of the drives. Here's some code that should show me the name of drive F:\:

import ctypes

kernel32 = ctypes.windll.kernel32
buf = ctypes.create_unicode_buffer(1024)

kernel32.GetVolumeNameForVolumeMountPointW(
    ctypes.c_wchar_p("F:\\"),
    buf,
    ctypes.sizeof(buf)
)

print buf.value

However, this outputs \\?\Volume{a8b6b3df-1a63-11e1-9f6f-0007e9ebdfbf}\. How can I get the string that windows shows in explorer (eg, KINGSTON, for a certain flash drive I own)?


EDIT:

Still not working:

volumeNameBuffer = ctypes.create_unicode_buffer(1024)
fileSystemNameBuffer = ctypes.create_unicode_buffer(1024)

kernel32.GetVolumeInformationW(
    ctypes.c_wchar_p("C:\\"),
    volumeNameBuffer,
    ctypes.sizeof(volumeNameBuffer),
    fileSystemNameBuffer,
    ctypes.sizeof(fileSystemNameBuffer)
)

This gives me this error:

WindowsError: exception: access violation reading 0x3A353FA0

Solution

  • Try the GetVolumeInformation function instead. It returns the volume label directly.