问题
I would like to get a list of the removable drivers that are plugged in to the computer.
I think it can be done by using some registry, but I don't know how exactly.
If there is another way I would like to hear about it.
Note: It's important that I will be able to separate the removable drives from the fixed drives.
回答1:
The algorithm is straightforward:
- Call [MS.Docs]: GetGetLogicalDriveStringsW function, which will return a string containing all the existing rootdirs (e.g. C:\\) separated by NULL (\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:
#!/usr/bin/env python3
import sys
import win32con
from win32api import GetLogicalDriveStrings
from win32file import GetDriveType
def get_drives_list(drive_types=(win32con.DRIVE_REMOVABLE,)):
drives_str = GetLogicalDriveStrings()
drives = [item for item in drives_str.split("\x00") if item]
return [item[:2] for item in drives if drive_types is None or GetDriveType(item) in drive_types]
def main():
drive_filters_examples = [
(None, "All"),
((win32con.DRIVE_REMOVABLE,), "Removable"),
((win32con.DRIVE_FIXED, win32con.DRIVE_CDROM), "Fixed and CDROM"),
]
for (drive_types_tuple, display_text) in drive_filters_examples:
drives = get_drives_list(drive_types=drive_types_tuple)
print("{0:s} drives:".format(display_text))
for drive in drives:
print("{0:s} ".format(drive), end="")
print("\n")
if __name__ == "__main__":
print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
main()
print("\nDone.")
Output:
[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q041465580]> "e:\Work\Dev\VEnvs\py_064_03.08.00_test0\Scripts\python.exe" code00.py Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] 64bit on win32 All drives: C: D: E: F: G: H: Removable drives: D: Fixed and CDROM drives: C: E: F: G: H: Done.
回答2:
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:\\']
来源:https://stackoverflow.com/questions/41465580/how-can-i-get-a-list-of-removable-drives-plugged-in-the-computer