使用.iter_rows时如何获取"current"行值?



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

目前,我有一种硬编码的方式来使其工作,使用一个 aux 变量 (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.rowrow.value,可以在迭代时返回我当前所在的行。

由于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

最新更新