Search code examples
pythonwindowshard-drive

Detect external hard drive after letter changed in Python


I am writing a Python program to scan and keep track of files on several external hard drives. It keeps the file path as a string in a local file. The problem is that sometimes when I plug the external HDD into different computer, the letter change, and the path stored earlier would be useless. I want to keep track of the drive and change the local records if the same hard drive is plugged in but the letter changed. Right now, I can think of two possibilities:

  1. Keep a identification file in the root of the drive and scan all drive letters to detect the drive with the right identification file.
  2. Scan all letter at the start to detect file in the same path as the local record. If found, identify the drive.

I want to know if there is any kind of existing identification for HDD (or partition) that I can use to access the drive (other than drive letter)?


Solution

  • Use Vendor ID and Device ID to identify the drive.

    #!/usr/bin/python
    import sys
    import usb.core
    # find USB devices
    dev = usb.core.find(find_all=True)
    # loop through devices, printing vendor and product ids in decimal and hex
    for cfg in dev:
      sys.stdout.write('Decimal VendorID=' + str(cfg.idVendor) + ' & ProductID=' + str(cfg.idProduct) + '\n')
      sys.stdout.write('Hexadecimal VendorID=' + hex(cfg.idVendor) + ' & ProductID=' + hex(cfg.idProduct) + '\n\n')
    

    Use PyUSB to Find Vendor and Product IDs for USB Devices

    Similare question : usb device identification