Detect external hard drive after letter changed in Python

Question:

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)?

Asked By: ndminh92

||

Answers:

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) + 'nn')

Use PyUSB to Find Vendor and Product IDs for USB Devices

Similare question : usb device identification

Answered By: user2226755

Yes, you can use the volume serial number to identify the HDD. The volume serial number is generated by Windows when you create or format a partition.

You should be able to do this through Python with the code below, replacing c with your desired partition.:

import subprocess

subprocess.check_output(["vol", "C:"])
Answered By: chirinosky

to find both usb and external harddrive

import wmi
import os
w = wmi.WMI()

for drive in w.Win32_LogicalDisk():
    print(drive)
    if drive.VolumeDirty == True:
        print (drive.Caption, drive.VolumeName, drive.DriveType)
Answered By: akash bbb
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.