1

I have a given file I need to find within a folder structure. There can and will be duplicate filenames within the file structure so I also need to return the file with the closest modified date to a given date. Simply returning the most recent file as shown below will not fit my need. This is one of those questions where there is no way to google and possibly return anything helpful.

def findClosestFile(name, path, date):
   result=[]
   for root, dirs, files in os.walk(path):
       if name in files:
           result.append(os.path.join(root, name))
return max(result, key=os.path.getmtime))
Maxwell
  • 149
  • 1
  • 12
  • 1) Make a list of tuples with `(mtime, name)` as the tuples; 2) sort that list on mtime 3) Use [bisect](https://docs.python.org/3/library/bisect.html) to find the insertion point of a tuple with the selected time; 4) Take the closer of left / right and that is the answer. – dawg Apr 01 '20 at 18:57

1 Answers1

3

If the date parameter should be close to the file date, the value

abs(date-os.path.getmtime(your_path))

should be as small as possible. Therefore, changing the last line of your function to

return min(result, key=lambda x:abs(date-os.getmtime(x)))

should solve the problem.

Jakob Schödl
  • 380
  • 2
  • 16
  • Thank you for that! Exactly what i was looking for! i knew a for loop would do it but i like to avoid loops wherever possible. – Maxwell Apr 01 '20 at 19:38