diff --git a/.gitignore b/.gitignore index 21637a0..9240015 100644 --- a/.gitignore +++ b/.gitignore @@ -192,3 +192,5 @@ Module.symvers Mkfile.old dkms.conf +# project specific +record_test_output diff --git a/record.py b/record.py index cd26bf4..b5df8d3 100644 --- a/record.py +++ b/record.py @@ -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): pass @@ -20,10 +28,7 @@ class Record: class RecordCollection(): def __init__(self, file): - if type(file) is str: - fd = open(file, "r") - elif hasattr(file, "read"): - fd = file + fd = filewrapper(file, "r") self._fromFile(fd) self._parent() @@ -76,3 +81,28 @@ class RecordCollection(): ret.append(self.objects[i]) 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() diff --git a/record_test.py b/record_test.py index 9202490..2e22e50 100644 --- a/record_test.py +++ b/record_test.py @@ -4,5 +4,6 @@ records = record.RecordCollection('datafile') entries = records.findEntrypoints() +records.write("record_test_output") print(records.objects) print(entries)