- 1 year ago
Get Drive-Letter of Storage Drive By Name/ID in Python
To get the drive letter of a storage drive in Python based on its name or ID, you can use the wmi
module to interact with the Windows Management Instrumentation (WMI) interface. Here's an example:
pythonimport wmi
def get_drive_letter_by_name(name):
wmi_obj = wmi.WMI()
for disk in wmi_obj.Win32_DiskDrive():
if disk.Caption == name:
for partition in disk.associators("Win32_DiskDriveToDiskPartition"):
for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
return logical_disk.DeviceID
return None
def get_drive_letter_by_id(id):
wmi_obj = wmi.WMI()
for disk in wmi_obj.Win32_DiskDrive():
if disk.DeviceID == id:
for partition in disk.associators("Win32_DiskDriveToDiskPartition"):
for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
return logical_disk.DeviceID
return None
# Example usage
drive_name = "MyDrive"
drive_id = "PHYSICALDRIVE1"
drive_letter = get_drive_letter_by_name(drive_name)
if drive_letter:
print(f"Drive letter for '{drive_name}': {drive_letter}")
else:
print(f"Drive '{drive_name}' not found.")
drive_letter = get_drive_letter_by_id(drive_id)
if drive_letter:
print(f"Drive letter for '{drive_id}': {drive_letter}")
else:
print(f"Drive with ID '{drive_id}' not found.")
In this example, the get_drive_letter_by_name
function searches for the specified drive name using the Caption
property of the Win32_DiskDrive
class in WMI. It then traverses the associations to retrieve the corresponding logical disk's device ID, which represents the drive letter.
Similarly, the get_drive_letter_by_id
function searches for the specified drive ID using the DeviceID
property of the Win32_DiskDrive
class. It follows the same associations to obtain the drive letter.
Make sure you have the wmi
module installed before running this code. You can install it using pip install wmi
. Note that this code is specific to Windows systems since it relies on the WMI interface, which is a Windows-specific technology.