add RecordCollection.write() method

This commit is contained in:
randomuser 2021-11-22 18:39:50 -06:00
parent d34d9272fe
commit 205674f2f2
3 changed files with 37 additions and 4 deletions

2
.gitignore vendored
View File

@ -192,3 +192,5 @@ Module.symvers
Mkfile.old Mkfile.old
dkms.conf dkms.conf
# project specific
record_test_output

View File

@ -1,3 +1,11 @@
def filewrapper(file, mode):
if type(file) is str:
return open(file, mode)
elif hasattr(file, "read"):
return file
else:
raise ValueError("need string or file descriptor object")
class FileParsingError(SyntaxError): class FileParsingError(SyntaxError):
pass pass
@ -20,10 +28,7 @@ class Record:
class RecordCollection(): class RecordCollection():
def __init__(self, file): def __init__(self, file):
if type(file) is str: fd = filewrapper(file, "r")
fd = open(file, "r")
elif hasattr(file, "read"):
fd = file
self._fromFile(fd) self._fromFile(fd)
self._parent() self._parent()
@ -76,3 +81,28 @@ class RecordCollection():
ret.append(self.objects[i]) ret.append(self.objects[i])
return ret return ret
def write(self, file):
fd = filewrapper(file, "w")
lines = []
for i in self.objects:
if self.objects[i].children:
lines.append(f"cat {self.objects[i].name}:")
else:
lines.append(f"rec {self.objects[i].name}:")
for j in self.objects[i].data:
lines.append(
f" {j}: {self.objects[i].data[j]}"
)
lines.append("")
lines.pop()
for i in range(len(lines)):
lines[i] += "\n"
fd.writelines(lines)
fd.close()

View File

@ -4,5 +4,6 @@ records = record.RecordCollection('datafile')
entries = records.findEntrypoints() entries = records.findEntrypoints()
records.write("record_test_output")
print(records.objects) print(records.objects)
print(entries) print(entries)