Skip to content

Commit

Permalink
Implement writing to csv
Browse files Browse the repository at this point in the history
  • Loading branch information
insolor committed Feb 25, 2024
1 parent e82b751 commit 4dc0b97
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
25 changes: 22 additions & 3 deletions csv_bisect_gui/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand All @@ -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)

Expand Down Expand Up @@ -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
Expand All @@ -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):
Expand Down
7 changes: 6 additions & 1 deletion csv_bisect_gui/bisect_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 4dc0b97

Please sign in to comment.