Repository navigation
Expand file tree
/
Copy pathfile_handler.py
More file actions
55 lines (45 loc) · 1.68 KB
/
Copy pathfile_handler.py
File metadata and controls
55 lines (45 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""JSON file I/O operations."""
import json
from tkinter import filedialog, messagebox
from config import FILE_TYPES
class FileHandler:
"""Handles opening, saving, and tracking the current JSON file."""
def __init__(self):
self.current_file = None
def new_file(self):
self.current_file = None
def open_file(self):
"""Open a JSON file and return parsed data, or None on cancel/error."""
path = filedialog.askopenfilename(filetypes=FILE_TYPES)
if not path:
return None
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
self.current_file = path
return data
except Exception as e:
messagebox.showerror("Error", f"Failed to open file:\n{e}")
return None
def save_file(self, data):
"""Save to current file, or prompt Save As if no file set."""
if self.current_file:
return self._write_file(self.current_file, data)
return self.save_file_as(data)
def save_file_as(self, data):
"""Prompt for a file path and save."""
path = filedialog.asksaveasfilename(
filetypes=FILE_TYPES, defaultextension=".json"
)
if not path:
return False
self.current_file = path
return self._write_file(path, data)
def _write_file(self, path, data):
try:
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent="\t", ensure_ascii=False)
return True
except Exception as e:
messagebox.showerror("Error", f"Failed to save file:\n{e}")
return False