对于将来可能遇到此问题的任何人(以及我自己将来在此问题上的参考),此答案将 Thaer A 在此线程和 Felix Heide此处的答案中的详细信息编译为基于其查找驱动器的更全面的方法卷名。
因此,假设您有一个驱动器,其名称Backup Drive
您不知道其字母,或者该驱动器是否已连接。您将执行以下操作:
首先,要检查驱动器是否已连接,我们将创建一个所有已连接驱动器名称的列表,以便稍后检查是否匹配Backup Drive
,并创建一个所有驱动器号的列表以供以后使用。还值得注意的是,在这个过程的大部分时间里使用它可能不是一个坏主意strip
,lower
但我不会在这里打扰它(至少现在是这样)。所以我们得到:
looking_for = "Backup Drive"
drive_names = []
drive_letters = []
接下来,让我们为以后设置我们的WMI
对象:
import wmi
c = wmi.WMI()
现在我们遍历所有连接的驱动器并填写我们的两个列表:
for drive in c.Win32_LogicalDisk ():
drive_names.append(str(drive.VolumeName))
drive_letters.append(str(drive.Caption))
我们还可以win32api
通过检查是否在此处使用模块向后验证
win32api.GetVolumeInformation(str(drive.Caption) + "\\")[0]
等于drive.VolumeName
。
然后我们可以检查驱动器是否连接,如果是则打印驱动器号:
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)]))
所以总的来说,我们也非常自由地加入strip
,lower
我们得到:
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())