如何在使用 .iter_rows 时获取 "current" 行值?
How to get the "current" row value while using .iter_rows?
我正在为我的研究小组开发访问控制系统,但在使用我的数据库对用户进行身份验证时遇到了困难。
我需要遍历一定数量的行(在 .xlsx 文件中)并检查我的值是否与列上的任何值匹配。如果是,将授予访问权限。否则,我需要打印一条错误消息。
我想知道是否有任何更聪明的方法来完成这项工作,因为据我检查 openpyxl 文档,它没有说明任何有助于在遍历行时提取当前行的值的内容。
目前我有一种硬编码的方式来让它工作,使用在迭代的每一行上递增的 aux 变量 (n)。每次迭代,'n' 被测试等于 sheet 上的行数。如果相等,则表示循环已到达 table 的末尾并且未找到用户。
# 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
returns 我在迭代时当前所在的行。
由于 ws.iter_rows()
returns 是一个可迭代对象,您可以使用 Python 的内置 enumerate
函数在遍历 [=20] 时获取索引=].它的工作方式几乎与您当前的幕后解决方案类似,但使代码更清晰、更易读。
您的代码如下所示:
# 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
我正在为我的研究小组开发访问控制系统,但在使用我的数据库对用户进行身份验证时遇到了困难。 我需要遍历一定数量的行(在 .xlsx 文件中)并检查我的值是否与列上的任何值匹配。如果是,将授予访问权限。否则,我需要打印一条错误消息。 我想知道是否有任何更聪明的方法来完成这项工作,因为据我检查 openpyxl 文档,它没有说明任何有助于在遍历行时提取当前行的值的内容。
目前我有一种硬编码的方式来让它工作,使用在迭代的每一行上递增的 aux 变量 (n)。每次迭代,'n' 被测试等于 sheet 上的行数。如果相等,则表示循环已到达 table 的末尾并且未找到用户。
# 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
returns 我在迭代时当前所在的行。
由于 ws.iter_rows()
returns 是一个可迭代对象,您可以使用 Python 的内置 enumerate
函数在遍历 [=20] 时获取索引=].它的工作方式几乎与您当前的幕后解决方案类似,但使代码更清晰、更易读。
您的代码如下所示:
# 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