I would like to get a list of the removable drivers that are plugged into the computer.
How can I do that with the pywin32 module in Python?
Note: It's important that I will be able to separate the removable drives from the fixed drives.
I just had a similar question myself. Isolating @CristiFati's answer to only removable drives, I knocked together this quick (very simple) function for any new visitors to this question:
Basically, just call the function and it will return a list
of all removable drives to the caller.
import win32api
import win32con
import win32file
def get_removable_drives():
drives = [i for i in win32api.GetLogicalDriveStrings().split('\x00') if i]
rdrives = [d for d in drives if win32file.GetDriveType(d) == win32con.DRIVE_REMOVABLE]
return rdrives
For example: A call to get_removable_drives()
will output:
['E:\\']
The algorithm is straightforward:
Call [MS.Docs]: GetGetLogicalDriveStringsW function, which will return a string containing all the existing rootdirs (e.g. C:\\) separated by NUL (\x00) chars
Iterate over the rootdirs and get each one's type using [MS.Docs]: GetDriveTypeW function
Filter the removable drives (having the type DRIVE_REMOVABLE)
This is how it looks in Python (using PyWin32 wrappers). Add any of win32con.DRIVE_* constants to drive_types tuple to get different drive types combinations:
code00.py:
Output:
As a side note, in my environment (at this point):
D: is a partition on an external (USB) HDD
H:, I: are partitions on a bootable USB stick (UEFI)
The rest are partitions on the (internal) SSD and / or HDD disks