Skip to content

Instantly share code, notes, and snippets.

@sasaujp
Created February 14, 2019 06:13
Show Gist options
  • Save sasaujp/b5ea0d13bb0afa5369325b453f060683 to your computer and use it in GitHub Desktop.
Save sasaujp/b5ea0d13bb0afa5369325b453f060683 to your computer and use it in GitHub Desktop.
ディレクトリの中で指定したパターンにマッチしないファイルとディレクトリを削除する。 / Delete files and directories that do not match the pattern specified in the directory.
from pathlib import Path
from typing import List
def _remove_files_that_do_not_match_patterns(path: Path, patterns: List[str]):
for pattern in patterns:
if path.match(pattern):
return True
else:
if not path.is_dir():
path.unlink()
return False
match_sub_path = False
for subpath in path.iterdir():
match_sub_path = _remove_files_that_do_not_match_patterns(subpath, patterns) or match_sub_path
if not match_sub_path:
path.rmdir()
return match_sub_path
def remove_files_that_do_not_match_patterns(root_path: str, patterns: List[str]):
_remove_files_that_do_not_match_patterns(Path(root_path), patterns)
remove_files_that_do_not_match_patterns('path/to/root_directory', ['hoge/*.py', 'fuga/'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment