Search code examples
pythonpython-3.xpython-osfileparsing

How to access the last filename in a directory in python


I'm trying to loop through some files in a directory. If the filename has two specific strings together, then I'm supposed to open and read those files for information. However, if none of the files have those two strings, I want to print an error message only once.

for filename in os.listdir(directory):
   if filename.find("<string1>") != -1 and filename.find("<string2>") != -1:
      #open file
   else:
      #print error message

I know doing this will print as many error messages as there are files in the directory (i.e. if there's 15 files with no matches, I'll get 15 error messages). But what I want is to only print an error message once after there aren't any matches in any of the N files in directory. I figured I could do something like this:

for filename in os.listdir(directory):
   if filename.find("<string1>") != -1 and filename.find("<string2>") != -1:
      #open file
   else:
      if filename[-1]: #if filename is last in directory
         #print error message

But I've discovered this doesn't work. How would I get an error message to print only after the last filename has been read and doesn't match?


Solution

  • A simple solution would be to initialize some boolean flag before your for loop, e.g. found = false

    If you find a file, set found = true. Then you can check the value of found after your for loop finishes and print the appropriate message based on its value.