Home > Software design >  How to list external drives with Python? (external USB HDD, external USB flash drive)
How to list external drives with Python? (external USB HDD, external USB flash drive)

Time:09-21

I have read Is there a way to list all the available Windows' drives? and Cross platform way to list disk drives on Linux, Windows and Mac using Python? and methods like:

import win32api
print(win32api.GetLogicalDriveStrings().split('\000'))

but how to limit this list to external USB storage devices only? (USB HDD, USB SSD, USB flash drive, etc.)

PS: is it possible with very few dependencies? (maybe just ctypes or win32api)

CodePudding user response:

If you check out https://devblogs.microsoft.com/scripting/inventory-drive-types-by-using-powershell/ and use power shell WMI commands, you can list all types of devices according to its id

import subprocess
import json


def list_drives():
    """
    Get a list of drives using WMI
    :return: list of drives
    """
    proc = subprocess.run(
        args=[
            'powershell',
            '-noprofile',
            '-command',
            'Get-WmiObject -Class Win32_LogicalDisk | Select-Object deviceid,volumename,drivetype | ConvertTo-Json'
        ],
        text=True,
        stdout=subprocess.PIPE
    )
    devices = json.loads(proc.stdout)
    for device in devices:
        if device['drivetype'] == 2:  # change to get drives with other types
            print(f'{device["deviceid"]}: {device["volumename"]}')


list_drives()

CodePudding user response:

wmi will do the task wmi python

import wmi

get = wmi.WMI()

drives_available = [wmi_object.deviceID for wmi_object in get.Win32_LogicalDisk() if wmi_object.description == "Removable Disk"]
print(drives_available)

Output

['E:']

using psutil

import psutil as ps
ext_drives = [i.mountpoint for i in ps.disk_partitions() if 'removable' in i.opts]
print(ext_drives)

Output

['E:']

uisng win32 api

import win32api
import win32con
import win32file

def get():
    all_drives = [i for i in win32api.GetLogicalDriveStrings().split('\x00') if i]
    out_drives = [d for d in all_drives if win32file.GetDriveType(d) == win32con.DRIVE_REMOVABLE]
    return out_drives



get()

Output

['E:']

CodePudding user response:

Here is a solution with only ctypes and no third-party module to pip install, inspired by Bhargav's solution:

import ctypes, string
bitmask = ctypes.windll.kernel32.GetLogicalDrives()
drives = [letter for i, letter in enumerate(string.ascii_uppercase) if bitmask & (1 << i)]
ext_drives = [letter for letter in drives if ctypes.windll.kernel32.GetDriveTypeW(letter   ':') == 2]  # DRIVE_REMOVABLE = 2
print(ext_drives)
  • Related