Skip to content

Index storage for Python

python
class IndexStorage:
    def __init__(self, file_path='index.cache'):
        self.file_path = file_path

    def _read_from_file(self, path: str) -> str:
        """Reads and returns the content of the specified file."""
        try:
            with open(path, 'r', encoding='utf-8') as file:
                return file.read()
        except FileNotFoundError:
            return None

    def _write_to_file(self, path: str, data: str) -> None:
        """Writes the given data to the specified file."""
        with open(path, 'w', encoding='utf-8') as file:
            file.write(data)

    def load_index(self) -> int:
        """Loads the index from the storage file. Returns -1 if the file does not exist or the content is not a valid integer."""
        content = self._read_from_file(self.file_path)
        if content is None:
            return -1
        try:
            return int(content)
        except ValueError:
            return -1

    def save_index(self, index: int) -> None:
        """Saves the given index to the storage file."""
        index_str = str(index)
        self._write_to_file(self.file_path, index_str)

if __name__ == '__main__':
    inds = IndexStorage()
    i = inds.load_index()
    if i != -1:
        print('loaded', i)
        inds.save_index(i + 1)
    else:
        print('Failed to load index.')

Released under the MIT License.