【发布时间】:2017-08-02 20:29:17
【问题描述】:
我编写了一个 Python 脚本,它从 Excel 工作表中读取值并遍历行。
但是,如果满足某个条件,我希望程序跳过一行。
我有一个 xml 文件,它的值决定了运行类型。在 python 代码中,我编写了一个 If / Else 块来将值转换为数字(见下文)
# If / Else to convert test_run_type text to a value
if test_run_type == "Regression":
test_run_type_value = '1'
elif test_run_type == "Smoke":
test_run_type_value = '2'
elif test_run_type == "Sanity":
test_run_type_value = '3'
接下来,我有遍历行的 for 循环(见下面的代码)
# Open Test Scenario Workbook; Instantiate worksheet object
wb = xlrd.open_workbook(os.path.join(test_case_directory, Product + '.xlsx'))
sh = wb.sheet_by_index(0)
## Begin For Loop to iterate through Test Scenarios
i = 1
rows = sh.nrows
empty_cell = False
for x in range(1, sh.nrows):
cell_val = sh.cell(i, 0).value
if cell_val == '':
# If Cell Value is empty, set empty_cell to True
empty_cell = True
else:
# If Cell Value is NOT empty, set empty_cell to False
empty_cell = False
regression_check = sh.cell_value(i, 3)
smoke_check = sh.cell_value(i, 4)
sanity_check = sh.cell_value(i, 5)
# If / Else Section to check if a test needs to be run
#### Program is running ALL rows & NOT skipping rows
if test_run_type_value == 3 and sanity_check == "False":
continue
else:
pass
if test_run_type_value == 2 and smoke_check == "False":
continue
else:
pass
if test_run_type_value == 1 and regression_check == "False":
continue
else:
pass
问题:我的预期是,如果连续发生以下情况之一,程序将跳过一行。
- test_run_type_value 为“3”且 sanity_check 等于 False
- test_run_type_value 为“2”,smoke_check 等于 False
- test_run_type_value 为“1”,regression_check 等于 False
但是,程序不会跳过任何行。
我截取了 Excel 工作表的屏幕截图。
根据工作表(见附图),当 test_run_type_value 为“3”但不是时,程序应该跳过第一行。程序遍历所有行(即使 test_run_type_value 为 1、2 或 3)
提前致谢
肯
【问题讨论】:
-
else: pass完全没有意义,你应该忽略它。 -
test_run_type_value = '3'反对test_run_type_value == 3
标签: python excel for-loop if-statement continue