repo-cloner/repo_cloner/lib/disk_stored_list.py

44 lines
985 B
Python
Raw Normal View History

from typing import Optional
import os
class DiskStoredList:
__file: Optional[str] = None
__items: Optional[list] = None
def __init__(self, file: str):
# file does not have to exist, but parent directory does
if not os.path.exists(file):
if not os.path.isdir(os.path.dirname(file)):
raise NotADirectoryError(f"Parent directory for file {file} does not exist!")
self.__file = file
self.__items = []
if os.path.exists(file):
self._load_from_file()
def _load_from_file(self):
with open(self.__file, 'r') as f:
for line in f.readlines():
line = line.strip()
if len(line):
self.__items.append(line)
def append(self, line: str):
with open(self.__file, 'a') as f:
self.__items.append(line)
f.write(f"{line}\n")
def count(self):
return len(self.__items)
def __contains__(self, line: str) -> bool:
return line in self.__items
def __iter__(self):
return self.__items.__iter__()
def __len__(self):
return len(self.__items)