pythonwindowsdrive-letter

Get Drive-Letter of Storage Drive By Name/ID in Python


I am trying to create some code that checks if a drive is connected and then edits files on that drive if it is. The issue is that the letter associated with that drive will not always be the same. Is there some way I can check if a drive with a given 'name' is connected or not and then get the letter for this drive similar to what this person is asking? Like if the drive I'm interested in is called Backup Drive, then could I check if a drive by this name is connected or not and find its assigned letter if it is? Or is there some sort of hardware ID specific to that drive that can accomplish the same thing?

Ultimately, I could also just go through every drive connected checking if a specific directory exists or not to find the letter assignment as well, but that's a rather obtuse solution and I'd like to avoid it if I can.

I'd also prefer that this be done in Python as that is what the rest of my code is in, but if a solution exists in Powershell or something else then I would consider outsourcing the work. I'm also happy to have a solution that is platform-dependent and works only on Windows as that is what I'm working in.


Solution

  • Did you try using the WMI module?

    import wmi
    
    DRIVE_TYPES = {
      0 : "Unknown",
      1 : "No Root Directory",
      2 : "Removable Disk",
      3 : "Local Disk",
      4 : "Network Drive",
      5 : "Compact Disc",
      6 : "RAM Disk"
    }
    
    c = wmi.WMI ()
    for drive in c.Win32_LogicalDisk ():
        # prints all the drives details including name, type and size
        print(drive)
        print (drive.Caption, drive.VolumeName, DRIVE_TYPES[drive.DriveType])