如何获得插入计算机的可移动驱动器列表?

How can I get a list of removable drives plugged in the computer?

我想获取插入计算机的可移动驱动程序的列表。

我认为可以通过使用一些注册表来完成,但我不知道具体如何。

如果有其他方法我想听听。

注意:重要的是我能够将可移动驱动器与固定驱动器分开。

算法很简单:

这是它在 Python 中的样子(使用 PyWin32 包装器)。将任何 win32con.DRIVE_* 常量添加到 drive_types 元组以获得不同的驱动器类型组合:

code00.py:

#!/usr/bin/env python

import sys

import win32con as wcon
from win32api import GetLogicalDriveStrings
from win32file import GetDriveType


def get_drives_list(drive_types=(wcon.DRIVE_REMOVABLE,)):
    drives_str = GetLogicalDriveStrings()
    drives = (item for item in drives_str.split("\x00") if item)
    return [item[:2] for item in drives if not drive_types or GetDriveType(item) in drive_types]


def main(*argv):
    drive_filters_examples = (
        (None, "All"),
        ((wcon.DRIVE_REMOVABLE,), "Removable"),
        ((wcon.DRIVE_FIXED, wcon.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("{:s} drives:".format(display_text))
        for drive in drives:
            print("{:s}  ".format(drive), end="")
        print("\n")


if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.")
    sys.exit(rc)

输出:

[cfati@CFATI-5510-0:e:\Work\Dev\Whosebug\q041465580]> "e:\Work\Dev\VEnvs\py_pc064_03.09_test0\Scripts\python.exe" ./code00.py
Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] 064bit on win32

All drives:
C:  D:  E:  F:  G:  H:  I:  L:  M:  N:

Removable drives:
H:  I:

Fixed and CDROM drives:
C:  D:  E:  F:  G:  L:  M:  N:


Done.

附带说明一下,在我的环境中(此时):

  • D: 是外部分区(USB ) 硬盘

  • H:,I: 是可启动 USB 记忆棒上的分区 (UEFI)

  • 其余是(内部)SSD 和/或 HDD 磁盘

    上的分区

我自己也有类似的问题。将@CristiFati 的答案隔离为仅可移动驱动器,我为这个问题的任何新访问者拼凑了这个快速(非常简单)的函数:

基本上,只要调用该函数,它就会 return 所有 可移动驱动器 中的 list 给调用者。

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

例如:调用get_removable_drives()将输出:

['E:\']