[英]How skip over an iteration in a for loop when an exception occurs Python
我正在创建一个脚本来解析文本文件并创建一个包含分隔符的行列表。 如果文本文件不包含分隔符,我想跳过 for 循环的迭代并返回错误。
这是我的代码。 我能够引发异常,但无法在没有打印语句的情况下迭代到列表的下一项。
import os
import glob
def read_file(fn):
''' input: filename
output: lines, step indexs, shorted filename'''
file_name = fn[:-4]
try:
file = open(fn, mode ='r')
lines = file.readlines()
except Exception as exc:
print(exc + 'for Filename' + file_name)
return file_name,lines
def get_indexs(lines):
#This is used to indicate the steps that have occurred.
step_indexs = []
x = 0
for line in lines:
x+=1
if '[step]'in line:
step_indexs.append(x)
# Testing to see if there is delimiter
try:
if len(step_indexs)<1:
raise ValueError('This Text File Did Not Detect a Delimiter')
except Exception as exc:
print(exc)
step_indexs.append(len(lines)+1)
for file in glob.glob("*.txt"):
file_name, lines = read_file(file)
step_indexs = get_indexs(lines)
print(file_name)
我正在寻找一个异常来停止 for 循环并引发异常,而不是打印文件名,而是通过 for 循环继续到 go。
如果要跳过 for 循环的迭代,请不要raise
异常然后catch
它,只需使用continue
关键字:
if len(step_indexs) < 1:
continue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.