首页 > 解决方案 > 如何在使用 .iter_rows 时获取“当前”行值?

问题描述

我正在为我的研究小组开发访问控制系统,并且在使用我的数据库对用户进行身份验证时遇到了困难。我需要遍历一定数量的行(在 .xlsx 文件中)并检查我的值是否与列上的任何值匹配。如果是,则将授予访问权限。否则,我需要打印一条错误消息。我想知道是否有任何更聪明的方法来完成这项工作,因为就我检查 openpyxl 文档而言,它没有说任何有助于在迭代行时提取当前行的值的内容。

目前我有一种硬编码的方式来使它工作,使用一个辅助变量(n),它在迭代的每一行上递增。每次迭代,'n' 被测试等于工作表上的行数。如果它相等,则意味着循环已到达表的末尾并且未找到用户。

# Checks if the UID was succesfully stored and is accessible
        for row in ws.iter_rows():
            if row[5].value == user.pin:
                print('Cadastro realizado com sucesso!')
                wb.close()
                del user
                break

            if n == ws.max_row:
                print('Usuário não autorizado')
                wb.close()
                gpio.output(10, gpio.LOW)
                del user
                n = 0
            n = n + 1

我一直在寻找一些替代方案,row.row或者row.value在迭代时返回我当前所在的行。

标签: pythonopenpyxl

解决方案


由于返回一个可迭代对象,因此您可以在遍历工作表ws.iter_rows()时使用 Python 的内置函数来获取索引。enumerate它几乎就像您当前的幕后解决方案一样工作,但使代码更清晰,更具可读性。

您的代码如下所示:

# Checks if the UID was succesfully stored and is accessible
    for idx, row in enumerate(ws.iter_rows()):
        if row[5].value == user.pin:
            print('Cadastro realizado com sucesso!')
            wb.close()
            del user
            break

        if idx + 1 == ws.max_row:
            print('Usuário não autorizado')
            wb.close()
            gpio.output(10, gpio.LOW)
            del user

推荐阅读