Question

I am attempting to relearn python, as it has been about 5 years since I have last messed with it. using a continue in the following search program is giving me a 'continue' not properly in loop error. Any suggestions?

# XML search function, 5/15/2014

import os, re

def main():

    path = 'C:/Python34/test'
    listing = os.listdir(path)
    for infile in listing:
        text = open(path + '/' + infile).read()
        match = re.search('hi', text)
    if match is None:
        continue
    print ('true')
    start = match.start()
    end = re.search('bye', text).start()
    print (text[start:end])
    print ('------------------------------------')

main()
Was it helpful?

Solution

If possible, avoid continue because it hides the logical flow of the program.

import os
import re

def main():
    path = r'C:\Python34\test'
    listing = os.listdir(path)
    for infile in listing:
        with open(os.path.join(path, infile)) as data:
            text = data.read()
        match = re.search('(hi.*?)bye', text, re.DOTALL)
        if match:
            print('true')
            print(match.group(1))
            print('------------------------------------')

if __name__ == '__main__':
    main()    

Use os.path.join to combine paths. Use with to open files, so they are closed automatically.

OTHER TIPS

for infile in listing:
    text = open(path + '/' + infile).read()
    match = re.search('hi', text)
    if match is None:
        continue

You outdented this part of it. Indent those last two lines as shown above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top