[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How to find directories that only contain a certain type of files (e
From: |
James Youngman |
Subject: |
Re: How to find directories that only contain a certain type of files (e.g., .txt)? |
Date: |
Sat, 16 Sep 2023 12:51:29 +0100 |
Sometimes the thing you need to do isn't a precise fit for the tools
(in this case, find) you have, and the Bourne shell is not quite
powerful enough to directly express the algorithm you have in mind, so
it can be better to fall back on a scripting language, perhaps
something like this:
#!/usr/bin/python3
import os
import os.path
import pathlib
import sys
from typing import Optional, Sequence
def find_only(extension: str, start_points: Sequence[str]) -> int:
for start in start_points:
for dirname, _subdirs, files in os.walk(start):
accept: Optional[bool] = None
for file in files:
path = pathlib.Path(os.path.join(dirname, file))
if path.suffix == extension:
if accept is None:
accept = True
else:
accept = False
break
if accept:
print(dirname)
return 0
def main(args: Sequence[str]) -> int:
if len(args) < 2:
program = args[0] if args[0] else 'findonly'
print(f"usage: {program} extension [start_point...]", file=sys.stderr)
return 1
extension = args[1]
if not extension.startswith('.'):
print("extension must start with a dot", file=sys.stderr)
return 1
return find_only(extension, args[2:])
if __name__ == '__main__':
sys.exit(main(sys.argv))