-
-
Save adamsilkey/61db1ed42764d3dd50d3f8df6fb3b1cf to your computer and use it in GitHub Desktop.
Line Terminator Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
""" | |
Silly implementation of a class which can emulate open() | |
while passing in a special lineterminator. | |
Not tested at all. | |
Author: Adam Silkey | |
Ref: https://discuss.python.org/t/41511 | |
""" | |
import re | |
class FunkyLines: | |
def __init__(self, s: str, lineterminator: str): | |
self.s = s | |
self.lineterminator = lineterminator | |
self._iter = re.finditer(self.lineterminator, self.s) | |
self._pos = 0 | |
def __next__(self): | |
if self._pos is None: | |
raise StopIteration | |
try: | |
start = self._pos | |
end, self._pos = next(self._iter).span() | |
return self.s[start:end] | |
except StopIteration: | |
start = self._pos | |
self._pos = None | |
return self.s[start:] | |
def __iter__(self): | |
return self | |
class _Open: | |
def __init__(self, _outer_class, fname, lineterminator): | |
self._outer_class = _outer_class | |
self.fname = fname | |
self.lineterminator = lineterminator | |
def __enter__(self): | |
self.file = open(self.fname, mode="r") | |
s = self.file.read() | |
return self._outer_class(s, self.lineterminator) | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
if self.file: | |
self.file.close() | |
@classmethod | |
def open(cls, fname, lineterminator): | |
return cls._Open(cls, fname, lineterminator) | |
if __name__ == '__main__': | |
records = 'a;b;c;d;e' | |
print(f"{records=}") | |
print('iterating over object') | |
for record in FunkyLines(records, ";"): | |
print(record) | |
with open('records', 'w') as f: | |
f.write(records) | |
print('iterating over file') | |
with FunkyLines.open('records', ";") as records: | |
for record in records: | |
print(record) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment