Skip to content

Instantly share code, notes, and snippets.

@WomB0ComB0
Created August 11, 2024 01:49
Show Gist options
  • Save WomB0ComB0/32abc671e1ca5f91ea1a2f89895d2e56 to your computer and use it in GitHub Desktop.
Save WomB0ComB0/32abc671e1ca5f91ea1a2f89895d2e56 to your computer and use it in GitHub Desktop.
Get the file names within a directory which match specified pattern
import os
import re
import sys
from typing import List
class FileSystem:
def __init__(self, path='.') -> None:
self.path = path
def filter_files(self, files, pattern) -> List[str]:
regex = re.compile(pattern)
return [f for f in files if regex.search(f)]
def files(self) -> List[str]:
try:
all_files: List[str] = []
for dirpath, _, filenames in os.walk(self.path):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
full_path = full_path.replace('\\', '/')
all_files.append(full_path)
return all_files
except OSError as e:
print(f"Error: Unable to access directory '{self.path}': {e}")
return []
def count(self) -> int:
return len(self.files())
def regex_files(self, pattern: str) -> List[str]:
pattern = re.sub(r'[^a-zA-Z0-9]', '', pattern)
regex = re.compile(pattern)
return [f for f in self.files() if regex.match(f)]
def __str__(self) -> str:
return f'FileSystem({self.path})'
def main() -> None:
fs = FileSystem()
print(f'Files in {fs}: {fs.count()}')
if len(sys.argv) > 1:
pattern = sys.argv[1]
print(f'Files matching pattern "{pattern}": {fs.regex_files(pattern)}')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment