From 4dc0b97be06cb11fa15173e2d876d03746670a8a Mon Sep 17 00:00:00 2001 From: insolor <2442833+insolor@users.noreply.github.com> Date: Sun, 25 Feb 2024 19:08:49 +0300 Subject: [PATCH] Implement writing to csv --- csv_bisect_gui/app.py | 25 ++++++++++++++++++++++--- csv_bisect_gui/bisect_tool.py | 7 ++++++- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/csv_bisect_gui/app.py b/csv_bisect_gui/app.py index 030abaa..7ee0715 100644 --- a/csv_bisect_gui/app.py +++ b/csv_bisect_gui/app.py @@ -6,6 +6,7 @@ from tkinter import filedialog, messagebox from alternative_encodings import cp866i, viscii +from tkinter_layout_helpers import pack_manager from csv_bisect_gui.bisect_tool import BisectTool @@ -16,13 +17,13 @@ class Window(tk.Tk): - bisect_tool: BisectTool + bisect_tool: BisectTool[str] file_types: list[tuple[str, str]] executable_path: Path | None csv_path: Path | None - csv_backup_path: Path | None + csv_backup_path: Path | None = None raw_data: list[bytes] | None @@ -34,9 +35,15 @@ def __init__(self, *args, **kwargs): self.combo_encodings = self.init_combo_encodings() - self.bisect_tool = BisectTool(self) + self.bisect_tool = BisectTool[str](self) self.bisect_tool.pack(fill=tk.BOTH, expand=True) + with pack_manager(self, side=tk.LEFT, expand=True, fill=tk.X, padx=1) as toolbar: + toolbar.pack_all( + ttk.Button(text="Write selection to csv", command=self.write_csv), + ttk.Button(text="Restore csv from backup", command=self.restore_backup), + ) + def init_combo_encodings(self): frame = tk.Frame(self) @@ -124,6 +131,15 @@ def load_csv(self): except UnicodeDecodeError: messagebox.showerror("ERROR", f"Failed to decode using {encoding} encoding") + def write_csv(self): + if not self.csv_path: + return + + with open(self.csv_path, "wb") as file: + for node in self.bisect_tool.selected_nodes: + for line in self.raw_data[node.slice]: + file.write(line) + def backup_csv(self): if self.csv_backup_path.exists() and self.csv_backup_path.read_bytes() == self.csv_path.read_bytes(): return @@ -133,6 +149,9 @@ def backup_csv(self): shutil.copyfile(self.csv_path, self.csv_backup_path) def restore_backup(self): + if not self.csv_backup_path: + return + shutil.copyfile(self.csv_backup_path, self.csv_path) def check_backup(self): diff --git a/csv_bisect_gui/bisect_tool.py b/csv_bisect_gui/bisect_tool.py index 4033b0d..6762ce5 100644 --- a/csv_bisect_gui/bisect_tool.py +++ b/csv_bisect_gui/bisect_tool.py @@ -48,9 +48,14 @@ def tree_text(self): else: return f"[{self.start} : {self.end}] ({self.size} strings)" + @property + def slice(self) -> slice: + return slice(self.start, self.end + 1) + @property def items(self) -> Iterable[T]: - return islice(self._all_items, self.start, self.end + 1) + s = self.slice + return islice(self._all_items, s.start, s.stop) @property def column_text(self) -> str: