gpt4 book ai didi

Python:如何仅搜索USB闪存驱动器?

转载 作者:行者123 更新时间:2023-12-01 05:42:57 25 4
gpt4 key购买 nike

我有一个 Python 脚本,设计为从 USB 闪存驱动器运行,如果从 PC 硬盘驱动器运行则无法运行,因此可以安全地假设所有副本都存在于连接的 USB 上。

我有另一个脚本设计为从计算机硬盘驱动器运行,它会查找这些 USB 脚本并以某种方式配置它们。显然,为了节省时间,当我知道它们仅位于 USB 上时,我不想搜索整个硬盘驱动器。有没有办法通过检查驱动器号等方式仅搜索连接的 USB 上的文件,跳过搜索本地驱动器?

最佳答案

下面是一些示例代码,用于使用 ctypes 确定 Windows 上每个事件逻辑驱动器的驱动器类型...

import ctypes

# Drive types
DRIVE_UNKNOWN = 0 # The drive type cannot be determined.
DRIVE_NO_ROOT_DIR = 1 # The root path is invalid; for example, there is no volume mounted at the specified path.
DRIVE_REMOVABLE = 2 # The drive has removable media; for example, a floppy drive, thumb drive, or flash card reader.
DRIVE_FIXED = 3 # The drive has fixed media; for example, a hard disk drive or flash drive.
DRIVE_REMOTE = 4 # The drive is a remote (network) drive.
DRIVE_CDROM = 5 # The drive is a CD-ROM drive.
DRIVE_RAMDISK = 6 # The drive is a RAM disk.

# Map drive types to strings
DRIVE_TYPE_MAP = { DRIVE_UNKNOWN : 'DRIVE_UNKNOWN',
DRIVE_NO_ROOT_DIR : 'DRIVE_NO_ROOT_DIR',
DRIVE_REMOVABLE : 'DRIVE_REMOVABLE',
DRIVE_FIXED : 'DRIVE_FIXED',
DRIVE_REMOTE : 'DRIVE_REMOTE',
DRIVE_CDROM : 'DRIVE_CDROM',
DRIVE_RAMDISK : 'DRIVE_RAMDISK'}


# Return list of tuples mapping drive letters to drive types
def get_drive_info():
result = []
bitmask = ctypes.windll.kernel32.GetLogicalDrives()
for i in range(26):
bit = 2 ** i
if bit & bitmask:
drive_letter = '%s:' % chr(65 + i)
drive_type = ctypes.windll.kernel32.GetDriveTypeA('%s\\' % drive_letter)
result.append((drive_letter, drive_type))
return result


# Test
if __name__ == '__main__':
drive_info = get_drive_info()
for drive_letter, drive_type in drive_info:
print '%s = %s' % (drive_letter, DRIVE_TYPE_MAP[drive_type])
removable_drives = [drive_letter for drive_letter, drive_type in drive_info if drive_type == DRIVE_REMOVABLE]
print 'removable_drives = %r' % removable_drives

...打印...

C: = DRIVE_FIXED
D: = DRIVE_FIXED
E: = DRIVE_CDROM
removable_drives = []

...插入 USB 内存棒之前...

C: = DRIVE_FIXED
D: = DRIVE_FIXED
E: = DRIVE_CDROM
F: = DRIVE_REMOVABLE
removable_drives = ['F:']

...之后。

获得可移动驱动器列表后,您可以简单地使用 os.walk()在每个驱动器上。

关于Python:如何仅搜索USB闪存驱动器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17028221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com