0

I am creating a script that parses text files and creates a list of which lines contain a delimiter. If the text file does not contain a delimiter I am I want to skip that iteration of the for loop and return an error.

Here is the code I have. I am able to raise an exception but am unable to iterate to the next item of the list without the print statement occurring.

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)

I am looking for an exception to stop the for loop and raise the exception and not print the file name but continue to go through the for loop.

1
  • You: "... but continue to go through the for loop." Commented Jul 27, 2020 at 15:47

1 Answer 1

5

If you want to skip an iteration of a for loop, don't raise an exception then catch it, just use the continue keyword:

if len(step_indexs) < 1:
    continue
Sign up to request clarification or add additional context in comments.

3 Comments

This is what I get when I add this to my function: SyntaxError: 'continue' not properly in loop
I believe it is. I think I am unable to do that in a function and that is the problem
Then what you should do is raise an exception, do not catch it inside the function, catch it in the for loop, and put the continue in the catch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.