Bootstrap FreeKB - Python (Scripting) - List files and directories
Python (Scripting) - List files and directories

Updated:   |  Python (Scripting) articles

Both os.listdir and os.walk can be used to find files and directories.

  • os.listdir is NOT recursive, meaning only the files and directories in the target directory will be returned
  • os.walk is recursive, meaning all of the files and directories at and below the target directory will be returned

In this example, the files and directories below /tmp will be listed, sorted alphabetically.

#!/usr/bin/python
import os

items = os.listdir("/tmp")
items.sort()

for item in items:
  print(item)

 

Something like this should be returned.

  • /tmp/bar (directory)
  • /tmp/foo (directory)
  • /tmp/my.txt (file)
bar
foo
my.txt

 

This isn't really all that great since you don't even know if the item is a file, a directory, or something else altogther. So I typically also include os.stat to list the item stats.

#!/usr/bin/python3
import os

items = os.listdir("/tmp")
items.sort()

for item in items:
  stat = os.stat(f"/tmp/{item}")
  print(f"/tmp/{item} = {stat}")

 

Which should now return something like this.

/tmp/foo = os.stat_result(st_mode=33188, st_ino=27901707, st_dev=64773, st_nlink=1, st_uid=65234, st_gid=100, st_size=0, st_atime=1701837284, st_mtime=1701837284, st_ctime=1701837284)

/tmp/bar = os.stat_result(st_mode=16877, st_ino=1, st_dev=65056, st_nlink=3, st_uid=0, st_gid=0, st_size=149, st_atime=1703235479, st_mtime=1703235479, st_ctime=1703235479)

 

And here is how to list only files.

#!/usr/bin/python3
import os

items = os.listdir("/tmp")
items.sort()

for item in items:
  if (os.path.isfile(f"/tmp/{item}")):
    print(item)

 

Or only directories.

#!/usr/bin/python3
import os

items = os.listdir("/tmp")
items.sort()

for item in items:
  if (os.path.isdir(f"/tmp/{item}")):
    print(item)

 

Here is an example of how you could append files containing "foo" at and below the /tmp directory to the matched_files list. In other words, this is a recursive search. 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 1b15f2 in the box below so that we can be sure you are a human.