mhartington mhartington - 4 years ago 190
Python Question

Python: create file if file does not exist in list

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download