How can I get the drive name in python

I have a list of valid drive letters, and I want to present the choice to the end user. I would like to show them the names of the disks. Here is some code that should show me the drive name 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 show in explorer (e.g. KINGSTON , for a specific flash drive that I have)?


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 
+5
source share
5 answers

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

+6
source

Why aren't you using win32api.GetVolumeInformation?

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

exits

 ('WINDOWS', 1992293715, 255, 65470719, 'NTFS') 
+5
source

Using the snippet above, 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 available for copy and paste.

+3
source

You can run the Windows command shell and parse the output.

 import subprocess def getDriveName(driveletter): return subprocess.check_output(["cmd","/c vol "+driveletter]).split("\r\n")[0].split(" ").pop() print getDriveName("d:") 

Works in Python 2.7

+1
source
  • returns driveLetter for a given driveLabel
  • returns notfound if driveLabel was not found

def findDriveByDriveLabel (driveLabel):

 drvArr = ['c:', 'd:', 'e:', 'f:', 'g:', 'h:', 'i:', 'j:', 'k:', 'l:'] for dl in drvArr: try: if (os.path.isdir(dl) != 0): val = subprocess.check_output(["cmd", "/c vol " + dl]) if (driveLabel in str(val)): return dl + "/" except: print("Error: findDriveByDriveLabel(): exception") return "notfound" 
0
source

Source: https://habr.com/ru/post/1383767/


All Articles