I studying for a Python course. I was finished working on task about creating a file class which can read, write lines to file. This class also needs magic methods (__add__
, __str__
, __iter__
, __next__
)
Can you review code and give a tip about improvements using the DRY principle (for example, how avoid to copy/paste with open
).
from tempfile import gettempdir
from os import path
import uuid
class File():
def __init__(self, file_path):
self.file_path = file_path
self.current_position = 0
def __iter__(self):
return self
def __next__(self):
try:
with open(self.file_path, 'r') as f:
f.seek(self.current_position)
line = f.readline().strip()
if not line:
self.current_position = 0
raise StopIteration('EOF')
self.current_position = f.tell()
return line
except IOError:
return 'Cant read next line'
def write(self, line):
try:
with open(self.file_path, 'w') as file_obj:
file_obj.write(line)
except IOError as err:
return 'Cant write to file: {0}'.format(err)
def read(self):
try:
with open(self.file_path, 'r') as file_obj:
return file_obj.read().strip()
except IOError:
return ''
def __add__(self, obj):
if isinstance(obj, File):
tmp_file_path = path.join(gettempdir(), str(uuid.uuid4()))
tmp_file = File(tmp_file_path)
tmp_file.write(self.read() + '\n' + obj.read())
return tmp_file
def __str__(self):
return self.file_path
f_obj = File('somepath1')
f_obj2 = File('somepath2')
f_obj3 = f_obj + f_obj2
for line in f_obj:
print(line)
print(f_obj3.read())