For readability, do this:

for dirpath, dirnames, filenames in os.walk(dir):
  ...

Then you can avoid referring to tuple indexes.