summaryrefslogtreecommitdiff
path: root/src/bcdd/PBNFile.py
diff options
context:
space:
mode:
authorMichał Klichowicz <emkael@tlen.pl>2023-09-30 12:40:40 +0200
committerMichał Klichowicz <emkael@tlen.pl>2023-09-30 12:40:40 +0200
commit518bdba985a913044e84e82713a8e76f5ddd3301 (patch)
tree6757ec4d785c07e2c3f34e70b5bd7326fe7c7a2c /src/bcdd/PBNFile.py
Initial import script
Diffstat (limited to 'src/bcdd/PBNFile.py')
-rw-r--r--src/bcdd/PBNFile.py43
1 files changed, 43 insertions, 0 deletions
diff --git a/src/bcdd/PBNFile.py b/src/bcdd/PBNFile.py
new file mode 100644
index 0000000..f5436ad
--- /dev/null
+++ b/src/bcdd/PBNFile.py
@@ -0,0 +1,43 @@
+import shutil
+import tempfile
+
+from .PBNBoard import PBNBoard
+
+class PBNFile(object):
+
+ def __init__(self, filename):
+ self._filename = filename
+ self.output_file = None
+ self.boards = []
+ lines = []
+ with open(self._filename) as pbn_file:
+ contents = pbn_file.readlines()
+ first_line = 1
+ for line_no in range(0, len(contents)):
+ line = contents[line_no].strip()
+ if not line:
+ if len(lines) > 0:
+ self.boards.append(PBNBoard(lines, first_line))
+ lines = []
+ first_line = line_no + 2
+ else:
+ lines.append(line)
+ if len(lines) > 0:
+ self.boards.append(PBNBoard(lines, first_line))
+ if not self.boards[0].has_field('Event'):
+ self.boards[0].write_event('')
+
+ def write_board(self, board):
+ if self.output_file is None:
+ self.output_file = tempfile.NamedTemporaryFile(
+ mode='w', delete=False)
+ for field in board.fields:
+ self.output_file.write(field.raw_field + '\r\n')
+ self.output_file.write('\r\n')
+
+ def save(self):
+ if self.output_file is None:
+ raise IOError('No boards written to PBN file, unable to save it.')
+ tmp_path = self.output_file.name
+ self.output_file.close()
+ shutil.move(tmp_path, self._filename)