53 lines
1.6 KiB
Python
53 lines
1.6 KiB
Python
#!/usr/bin/python3
|
|
|
|
import csv
|
|
import sys
|
|
|
|
class Record:
|
|
"""A record containing one or more fields."""
|
|
def __init__(self, fields):
|
|
self._fields = fields
|
|
@property
|
|
def fields(self):
|
|
return self._fields
|
|
|
|
class CSVFile:
|
|
"""A comma-separated values file."""
|
|
def __init__(self, filename):
|
|
self._filename = filename
|
|
def store(self, records):
|
|
"""Store the records to this file."""
|
|
writer = csv.writer(open(self._filename, "w"), delimiter=':')
|
|
for rec in records:
|
|
writer.writerow(rec.fields)
|
|
def load(self):
|
|
"""Read this file as a list of records."""
|
|
reader = csv.reader(open(self._filename, "r"), delimiter=':')
|
|
return [Record(row) for row in reader]
|
|
|
|
class FileStorage:
|
|
"""A file (or file-like object) in a certain format."""
|
|
def __init__(self, fmt, filename):
|
|
if fmt == "csv":
|
|
self._backend = CSVFile(filename)
|
|
else:
|
|
raise ValueError("{0}: not a supported backend".format(fmt))
|
|
def store(self, records):
|
|
"""Store the records."""
|
|
self._backend.store(records)
|
|
def load(self):
|
|
"""Load the records."""
|
|
return self._backend.load()
|
|
|
|
def main(filename):
|
|
fs = FileStorage("csv", filename)
|
|
l = [Record([0, 1, 2, 3]), Record([4, 5, 6, 7])]
|
|
fs.store(l)
|
|
m = fs.load()
|
|
for a, b in zip(l, m):
|
|
for c, d in zip(a.fields, b.fields):
|
|
if str(c) != str(d):
|
|
raise ValueError("{0} and {1} differ!".format(c, d))
|
|
|
|
if __name__ == '__main__':
|
|
main(sys.argv[1])
|