1

I'm getting a list of files in a project, which can all range from src/app.ts to src/component/app/app.ts. What I'm looking to do is:

  • loop over each file in the list,
  • see if it matches a pattern of a specific config,
  • and if the file does not exist, write it to disk.

Currently I have:

m = re.compile(r'(ts|js)config.json$')
for file in files:
    if m.search(file):
        return True
    else:
        self.writeFile()

Which works, but it calls write multiple times when there is not match. How would I only call write after the checks are done?

2 Answers 2

1

You could just unindent your else block so it applies to for:

for file in files:
    if m.search(file):
        return True
else:
    self.writeFile()

note that in that case it's not as interesting as with the break case, you could simply write:

for file in files:
    if m.search(file):
        return True
self.writeFile()

since if pattern matches it returns so writeFile is not reached.

Sign up to request clarification or add additional context in comments.

Comments

1

You could move out writing the file to after all the checks are exhausted:

m = re.compile(r'(ts|js)config.json$')
for file in files:
    if m.search(file):
        return True

self.writeFile()

Comments

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.