use context managers in RecordCollection.__init__() and RecordCollection.write()

This commit is contained in:
randomuser 2021-11-22 18:43:08 -06:00
parent f66776c9bb
commit a0ebba802e
1 changed files with 19 additions and 23 deletions

View File

@ -28,12 +28,9 @@ class Record:
class RecordCollection(): class RecordCollection():
def __init__(self, file): def __init__(self, file):
fd = filewrapper(file, "r") with filewrapper(file, "r") as fd:
self._fromFile(fd)
self._fromFile(fd) self._parent()
self._parent()
fd.close()
def _fromFile(self, fd): def _fromFile(self, fd):
lines = [i.rstrip() for i in fd.readlines()] lines = [i.rstrip() for i in fd.readlines()]
@ -85,26 +82,25 @@ class RecordCollection():
return ret return ret
def write(self, file): def write(self, file):
fd = filewrapper(file, "w") with filewrapper(file, "w") as fd:
lines = [] lines = []
for i in self.objects: for i in self.objects:
if self.objects[i].children: if self.objects[i].children:
lines.append(f"cat {self.objects[i].name}:") lines.append(f"cat {self.objects[i].name}:")
else: else:
lines.append(f"rec {self.objects[i].name}:") lines.append(f"rec {self.objects[i].name}:")
for j in self.objects[i].data: for j in self.objects[i].data:
lines.append( lines.append(
f" {j}: {self.objects[i].data[j]}" f" {j}: {self.objects[i].data[j]}"
) )
lines.append("") lines.append("")
lines.pop() lines.pop()
for i in range(len(lines)): for i in range(len(lines)):
lines[i] += "\n" lines[i] += "\n"
fd.writelines(lines) fd.writelines(lines)
fd.close()