You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.7 KiB
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""Реализация класса 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