Read and write dataclasses.
dataclass_io
provides similar functionality to the standard library's csv.DictReader
and csv.DictWriter
, and adds type safety.
dataclass_io
may be installed via pip
:
pip install dataclass_io
from dataclasses import dataclass
from dataclass_io import DataclassReader
@dataclass
class MyData:
foo: int
bar: str
with open("test.tsv", "w") as testfile:
testfile.write("foo\tbar\n")
testfile.write("1\tabc\n")
testfile.write("2\tdef\n")
with open("test.tsv", "r") as fin:
reader = DataclassReader(fin, MyData)
for record in reader:
print(record.foo)
from dataclasses import dataclass
from dataclass_io import DataclassWriter
@dataclass
class MyData:
foo: int
bar: str
with open("test.tsv", "w") as fout:
writer = DataclassWriter(fout, MyData)
for i in range(3):
record = MyData(foo=i, bar="something")
writer.write(record)