input_output.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from more_itertools import islice_extended
  2. from pathlib import Path
  3. from typing import Callable, Generator, Any, Iterable, Optional, Literal
  4. def read_rows(
  5. pathfile:str|Path,
  6. templete:Optional[Callable[[str], Any]]=None,
  7. mode:Literal['r', 'rb']='r',
  8. islice:slice=slice(0,None,1),
  9. encoding:str='utf-8') -> Generator[str | Any, None, None]:
  10. """Возращает генератор по строчно"""
  11. with open(file=pathfile, mode=mode, encoding=encoding) as file:
  12. for row in islice_extended(file)[islice]:
  13. try:
  14. yield templete(row) if templete else row
  15. except GeneratorExit:
  16. break
  17. except:
  18. continue
  19. def write_file(
  20. pathfile:str|Path,
  21. write:Iterable[Any]|str,
  22. mode:Literal['a', 'w', 'wb']='a',
  23. encoding:str='utf-8',
  24. addN:bool=False) -> None:
  25. """ Записывает в файл"""
  26. with open(file=pathfile, mode=mode, encoding=encoding) as file:
  27. if isinstance(write, str):
  28. file.write(write + '\n') if addN else file.write(write)
  29. else:
  30. file.writelines((str(elem + '\n') for elem in write)) if addN else file.writelines(write)
  31. def my_input2(end: str = '',
  32. inside_string: Optional[Callable[[str], Any]] = None,
  33. execute_with_element: Callable[[str], Any] = lambda n: n) -> Generator[str | Any, None, None]:
  34. print('\033[92m' + "---> " + '\033[1m', end='')
  35. for row in list(iter(input, end)):
  36. if inside_string:
  37. for item_strok in inside_string(row):
  38. yield execute_with_element(item_strok)
  39. else:
  40. yield execute_with_element(row)