Bootstrap FreeKB - Python (Scripting) - Find files using os.walk
Python (Scripting) - Find files using os.walk

Updated:   |  Python (Scripting) articles

Here is the minimal boilterplate code without error handling to find all of the files and directories at and below the /tmp directory using os.walk. In other words, this is a recursive search.

#!/usr/bin/python3
import os

for root, dirs, files in os.walk("/tmp"):
  for directory in dirs:
    print(f"just the directory name = {directory}")
    print(f"full path to the directory = {os.path.join(root, directory)}")

  for filename in files:
    print(f"just the filename = {filename}")
    print(f"full path to the file = {os.path.join(root, filename)}")

 

Here is a more practical example, with try/except/else error handling of how you could append files containing "foo" at and below the /tmp directory to the matched_files list. For example, if there is a file named foo.txt in the /tmp directory, the matched_files list will contain /tmp/foo.txt.

#!/usr/bin/python3
import os
import re

target_directory = "/tmp"

if not os.path.exists(target_directory):
  print(f"directory {target_directory} does NOT exist")
else:
  print(f"directory {target_directory} exists")

  matched_files = []

  for root, dirs, files in os.walk(target_directory):
    for name in files:
      if re.match('foo', name):
        matched_files.append(os.path.join(root, name))

  print(f"matched_files = {matched_files}")

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter f17e7c in the box below so that we can be sure you are a human.