For anyone who might have this problem in the future (and for my own future reference on this issue), this answer compiles details from answers by Thaer A on this thread and Felix Heide here into a more comprehensive way of finding a drive based on its volume name.
So let's assume you have a drive with the name Backup Drive
that you do not know the letter of, or whether or not the drive is even connected. You would do the following:
First, to check if the drive is connected we will create a list of all the drive names that are connected to check if any match Backup Drive
later on and a list of all of the drive letters for later use. It is also worth noting that it's probably not a bad idea to use strip
and lower
for much of this process, but I'm not going to bother with that here (at least for now). So we get:
looking_for = "Backup Drive"
drive_names = []
drive_letters = []
Next, let's set up our WMI
object for later:
import wmi
c = wmi.WMI()
Now we loop through all of the connected drives and fill in our two lists:
for drive in c.Win32_LogicalDisk ():
drive_names.append(str(drive.VolumeName))
drive_letters.append(str(drive.Caption))
We can also backwards verify here with the win32api
module by checking if
win32api.GetVolumeInformation(str(drive.Caption) + "\\")[0]
is equal to drive.VolumeName
.
Then we can check if the drive is connected or not and print the drive letter if it is:
if looking_for not in drive_names:
print("The drive is not connected currently.")
else:
print("The drive letter is " + str(drive_letters[drive_names.index(looking_for)]))
So in total, also adding in strip
and lower
very liberally, we get:
import wmi
import win32api, pywintypes # optional
looking_for = "Backup Drive"
drive_names = []
drive_letters = []
c = wmi.WMI()
for drive in c.Win32_LogicalDisk ():
drive_names.append(str(drive.VolumeName).strip().lower())
drive_letters.append(str(drive.Caption).strip().lower())
# below is optional
# need a try catch because some drives might be empty but still show up (like D: drive with no disk inserted)
try:
if str(win32api.GetVolumeInformation(str(drive.Caption) + "\\")[0]).strip().lower() != str(drive.VolumeName).strip().lower():
print("Something has gone horribly wrong...")
except pywintypes.error:
pass
if looking_for.strip().lower() not in drive_names:
print("The drive is not connected currently.")
else:
print("The drive letter is " + str(drive_letters[drive_names.index(looking_for.strip().lower())]).upper())