HasteBin0

Appreciate How Far a Project has Come

Jul 17th, 2020
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. #!/usr/bin/python3
  2. from os import walk
  3. from os.path import isdir, isfile, join, abspath
  4. from typing import Tuple
  5.  
  6.  
  7. gf_exclude: Tuple = ('__pycache__', '.idea')
  8.  
  9.  
  10. def gen_filenames(path: str) -> [str]:
  11.     for directory, _, filenames in walk(path):
  12.         if any(x in directory for x in gf_exclude):
  13.             continue
  14.         for _filename in filenames:
  15.             yield join(directory, _filename)
  16.  
  17.  
  18. def report(_filename: str) -> Tuple[int, int]:
  19.     print(f'"{_filename}" ', end = '')
  20.     try:
  21.         file = open(_filename, 'r', encoding = 'UTF-8')
  22.     except PermissionError:
  23.         print('Gave permission error')
  24.         raise
  25.     _lines: int = 0
  26.     _characters: int = 0
  27.     try:
  28.         for line in file.readlines():
  29.             _lines += 1
  30.             _characters += len(line)
  31.     except UnicodeDecodeError:
  32.         print('Gave unicode error')
  33.         raise
  34.     finally:
  35.         file.close()
  36.     print(
  37.         f'Has {_lines} line{"s" if _lines != 1 else ""} and {_characters} character{"s" if _lines != 1 else ""} in it.')
  38.     return _lines, _characters
  39.  
  40.  
  41. u_in: str
  42. file_not_dir: bool
  43.  
  44. while True:
  45.     u_in = input('File or folder: ')
  46.     file_not_dir = isfile(u_in)
  47.     if file_not_dir:
  48.         break
  49.     elif isdir(u_in):
  50.         file_not_dir = False
  51.         break
  52.  
  53. if file_not_dir:
  54.     try:
  55.         report(u_in)
  56.     except PermissionError:
  57.         pass
  58. else:
  59.     lines: int = 0
  60.     characters: int = 0
  61.     files_seen: int = 0
  62.     files_reported: int = 0
  63.     for filename in gen_filenames(u_in):
  64.         files_seen += 1
  65.         try:
  66.             l, c = report(filename)
  67.             files_reported += 1
  68.             lines += l
  69.             characters += c
  70.         except (PermissionError, UnicodeDecodeError):
  71.             pass
  72.     print(
  73.         f'In total, {files_seen} file{"s" if files_seen != 1 else ""} were detected and '
  74.         f'{files_reported} thereof {"were" if files_reported != 1 else "was"} examined.\n'
  75.         f'A total of {str(lines) + " lines" if lines != 1 else "1 line"} and '
  76.         f'{str(characters) + " characters" if characters != 1 else "1 character"} '
  77.         f'were detected')
  78.  
  79. input(
  80.     f'"{abspath(u_in)}"\n'
  81.     'Hit [Enter]. ')
Add Comment
Please, Sign In to add comment