处理来自多个驱动器的项目列表

2024-10-01 04:56:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表,如下图所示。我将列表传递到python函数中,以处理列表中的每个项目。我需要访问多个系统驱动器来处理列表。我当前的程序每次都会打开驱动器。这是低效的。仅当列表中的当前项来自与上次处理的项不同的驱动器时,我才想打开该驱动器

(1, 18911232, 'af1a83d6b18bf3e065be82cf44246037', 'D')
(2, 18911744, 'd5cedca078545cbcb0b2a9b514f9b92d', 'D')
(3, 18912256, '457ee2f5dc6f95b09599fc3f479878b6', 'D')
(4, 27076608, '8fb1ee8d6d8df00e53055e0eb48ef2e5', 'E')
(5, 27077120, 'a9ea5ccfebe4d6b3ecdd429518fff688', 'E')
(6, 27077632, 'ff722e8bb3c731ece625f882a090f100', 'E')
(7, 19604324352, 'd1fd613c04c983d73d79027f2a3425f9', 'C')
(8, 19604324864, '6f51f480b2ad733f20a54c8d3f5dd38c', 'C')
(9, 19604325376, '066fdaddf301b83402934e5783a3eec3', 'C')

def check(oldList):
    newList = []#To hold processed list
    try:
        for item in oldList:
            drive = item[3]
            volume = r"\\." + '\\'+ drive + ':' #Constructing string to open the drive.                  
            with open(volume, 'rb') as disk: #Open drive
                disk.seek(item[2])#Move to sector address on disk
                sector_data = disk.read(512) #Read sector data (512 bytes)
                sectorHash = md5HashFunc(sector_data)#Hash sector data
                if sectorHash==item[3]:  
                    pass #If data matches, do nothing - sector still intact
                else:
                    newList.append(item[1])
    except Exception as err:
        logging.exception(err)
        logging.info('=======================================================\n')
        notificationMessage('An error occured and has been logged, see log for details.')
    return newList #Return new list.

Tags: to列表fordataasdriveopenitem
1条回答
网友
1楼 · 发布于 2024-10-01 04:56:19

want to open the drive only if the current item in the list is from a different drive from the last item processed

存储最后一次看到的驱动器,然后检查它是否在循环过程中发生变化

比如说

drive = None
prevDrive = None
disk = None
for item in oldList:
    drive = item[3]
    if drive != prevDrive
        volume = r"\\." + '\\'+ drive + ':'
        if disk is not None:  # if previously assigned
            disk.close()
        disk = open(volume, 'rb')
    
    # do work
    disk.seek(item[2])

    prevDrive = drive
if disk is not None:
    disk.close()

不过,这只适用于相对排序的驱动器列表

另一种方法是存储文件句柄的字典

drive_map = {item[3]: open(r"\\." + '\\'+ item[3] + ':', 'rb') for item in oldList}
for item in oldList:
    disk = drive_map[item[3]]
    # do work
    disk.seek(item[2])
     
# make sure to close all the files when done
for _, f in drive_map.items():
    f.close()

还不确定为什么要检查扇区哈希值是否等于驱动器值,因为哈希值通常不是单个字符

相关问题 更多 >