Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 951
Eric Avatar asked Nov 29 '11 23:11

Eric


3 Answers

Why don't you use win32api.GetVolumeInformation?

import win32api
win32api.GetVolumeInformation("C:\\")

outputs

('WINDOWS', 1992293715, 255, 65470719, 'NTFS')
like image 190
Felix Heide Avatar answered Oct 29 '22 04:10

Felix Heide


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

like image 7
Greg Hewgill Avatar answered Oct 29 '22 05:10

Greg Hewgill


Using the above fragment, I filled in the missing(optional, null) arguments as a quick helper:

import ctypes
kernel32 = ctypes.windll.kernel32
volumeNameBuffer = ctypes.create_unicode_buffer(1024)
fileSystemNameBuffer = ctypes.create_unicode_buffer(1024)
serial_number = None
max_component_length = None
file_system_flags = None

rc = kernel32.GetVolumeInformationW(
    ctypes.c_wchar_p("F:\\"),
    volumeNameBuffer,
    ctypes.sizeof(volumeNameBuffer),
    serial_number,
    max_component_length,
    file_system_flags,
    fileSystemNameBuffer,
    ctypes.sizeof(fileSystemNameBuffer)
)

print volumeNameBuffer.value
print fileSystemNameBuffer.value

This should be copy-and-paste-able.

like image 7
Nicholas Orlowski Avatar answered Oct 29 '22 06:10

Nicholas Orlowski