grokking-algorithms/chapter7/bfs_dirtrav.py

32 lines
701 B
Python
Raw Normal View History

2024-01-12 10:56:00 +00:00
import logging
from collections import deque
from pathlib import Path
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
2024-01-12 12:19:51 +00:00
EXT = ".rb"
2024-01-12 10:56:00 +00:00
scripts_path = Path.home() / "scripts"
2024-01-12 12:19:51 +00:00
def files_with_extension(start_directory):
2024-01-12 10:56:00 +00:00
queue = deque()
2024-01-12 12:19:51 +00:00
queue.append(start_directory)
2024-01-12 10:56:00 +00:00
while queue:
2024-01-12 12:19:51 +00:00
items = queue.popleft()
2024-01-12 10:56:00 +00:00
2024-01-12 12:19:51 +00:00
for item in items.glob("*"):
2024-01-12 12:32:53 +00:00
# if item is a file and has extension EXT then print
2024-01-12 12:19:51 +00:00
if item.is_file():
if item.suffix == EXT:
print(item)
2024-01-12 10:56:00 +00:00
2024-01-12 12:19:51 +00:00
# otherwise append directory to the queue
else:
queue.append(item)
2024-01-12 10:56:00 +00:00
2024-01-12 12:19:51 +00:00
files_with_extension(scripts_path)