|
|
"""Реализация класса File с магическими методами"""
|
|
|
|
|
|
from os.path import join
|
|
|
from tempfile import gettempdir
|
|
|
|
|
|
|
|
|
class File:
|
|
|
"""Класс для работы с файлами"""
|
|
|
|
|
|
def __init__(self, file_path: "str"):
|
|
|
"""Конструктор базового класса"""
|
|
|
|
|
|
self.file_path: "str" = file_path
|
|
|
self.current_position: "int" = 0
|
|
|
|
|
|
def write(self, line: "str") -> None:
|
|
|
"""Запись строки в файл"""
|
|
|
|
|
|
with open(self.file_path, "w", encoding="utf-8") as des:
|
|
|
des.write(line)
|
|
|
|
|
|
def read(self) -> "str":
|
|
|
"""Чтение файла"""
|
|
|
|
|
|
try:
|
|
|
with open(self.file_path, encoding="utf-8") as des:
|
|
|
content: "str" = des.read()
|
|
|
|
|
|
except IOError:
|
|
|
content = ""
|
|
|
|
|
|
return content
|
|
|
|
|
|
def __add__(self, obj: "File") -> "File":
|
|
|
"""Сложение двух объектов"""
|
|
|
|
|
|
new_file = type(self)(join(gettempdir(), "temp.txt"))
|
|
|
new_file.write(self.read() + obj.read())
|
|
|
|
|
|
return new_file
|
|
|
|
|
|
def __str__(self) -> "str":
|
|
|
"""Строковое представление объекта"""
|
|
|
|
|
|
return self.file_path
|
|
|
|
|
|
def __iter__(self) -> "File":
|
|
|
"""Метод возращающий итератор"""
|
|
|
|
|
|
return self
|
|
|
|
|
|
def __next__(self) -> "str":
|
|
|
with open(self.file_path, "r", encoding="utf-8") as des:
|
|
|
des.seek(self.current_position)
|
|
|
|
|
|
line: "str" = des.readline()
|
|
|
|
|
|
if not line:
|
|
|
self.current_position = 0
|
|
|
raise StopIteration("EOF")
|
|
|
|
|
|
self.current_position = des.tell()
|
|
|
|
|
|
return line
|