Python:如何只搜索USB闪存盘?

时间:2013-06-10 16:07:28

标签: python usb file-search

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

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

2 个答案:

答案 0 :(得分:2)

以下是使用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()即可。

答案 1 :(得分:0)

我认为您可以在post

中找到答案

他使用pyUsb来操作usb文件。希望这会有所帮助。