initial commit
This commit is contained in:
commit
1a12e6d3c5
19 changed files with 494 additions and 0 deletions
50
src/pen_tracker/engine.py
Normal file
50
src/pen_tracker/engine.py
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import csv
|
||||
import os
|
||||
|
||||
class PenTracker:
|
||||
def __init__(self, storage_file='Pens.csv'):
|
||||
self.storage_file = storage_file
|
||||
self.headers = [
|
||||
'Make', 'Model', 'Date-Purchased', 'Vendor', 'Nib',
|
||||
'Nib-Material', 'Body', 'Cap', 'Post',
|
||||
'Current-Ink', 'Inked-date', 'Notes'
|
||||
]
|
||||
self.pens = self.load_data()
|
||||
|
||||
def _sort_pens(self):
|
||||
"""Sorts the pens list by Make, then by Model alphabetically."""
|
||||
self.pens.sort(key=lambda x: (x.get('Make', '').lower(), x.get('Model', '').lower()))
|
||||
|
||||
def load_data(self):
|
||||
"""Loads data from the CSV file."""
|
||||
if not os.path.exists(self.storage_file):
|
||||
self._create_empty_csv()
|
||||
return []
|
||||
|
||||
pens = []
|
||||
try:
|
||||
# Standard, clean way to open the file
|
||||
with open(self.storage_file, mode='r', encoding='utf-8-sig') as f:
|
||||
reader = csv.DictReader(f)
|
||||
for row in reader:
|
||||
# Strip whitespace from keys and values, handle empty values
|
||||
clean_row = {k.strip(): (v.strip() if v else "N/A") for k, v in row.items()}
|
||||
pens.append(clean_row)
|
||||
self._sort_pens()
|
||||
except Exception as e:
|
||||
print(f"[!] Error loading CSV: {e}")
|
||||
return pens
|
||||
|
||||
def _create_empty_csv(self):
|
||||
"""Creates the CSV file with headers if it is missing."""
|
||||
with open(self.storage_file, mode='w', newline='', encoding='utf-8') as f:
|
||||
writer = csv.DictWriter(f, fieldnames=self.headers)
|
||||
writer.writeheader()
|
||||
|
||||
def save_data(self):
|
||||
"""Sorts the data before writing to ensure persistent alphabetical order."""
|
||||
self._sort_pens()
|
||||
with open(self.storage_file, mode='w', newline='', encoding='utf-8') as f:
|
||||
writer = csv.DictWriter(f, fieldnames=self.headers)
|
||||
writer.writeheader()
|
||||
writer.writerows(self.pens)
|
||||
Loading…
Add table
Add a link
Reference in a new issue