60 lines
2.0 KiB
Python
60 lines
2.0 KiB
Python
# tabularfile.loader - tabular file for humans
|
|
# Copyright (C) 2020 Entr'ouvert
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify it
|
|
# under the terms of the GNU Affero General Public License as published
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
import contextlib
|
|
import io
|
|
|
|
from .common import TabularFileError
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def fh_from_path_or_file(path_or_file):
|
|
if isinstance(path_or_file, bytes):
|
|
yield io.BytesIO(path_or_file)
|
|
else:
|
|
if isinstance(path_or_file, io.TextIOBase):
|
|
raise TabularFileError('file handle must be a bytes stream')
|
|
if isinstance(path_or_file, io.IOBase):
|
|
if not path_or_file.readable or not path_or_file.seekable:
|
|
raise TabularFileError('file handle must be readable and seekable')
|
|
yield path_or_file
|
|
else:
|
|
with open(path_or_file, 'rb') as fh:
|
|
yield fh
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def load(path_or_file, format=None, **kwargs):
|
|
from . import ods, csv
|
|
|
|
with fh_from_path_or_file(path_or_file) as fh:
|
|
offset = fh.tell()
|
|
header = fh.read(1024)
|
|
fh.seek(offset)
|
|
|
|
if format is None:
|
|
if header[:4] == b'PK\x03\x04':
|
|
format = 'ods'
|
|
else:
|
|
format = 'csv'
|
|
|
|
if format == 'ods':
|
|
yield ods.Reader(fh, **kwargs)
|
|
elif format == 'csv':
|
|
yield csv.Reader(fh, **kwargs)
|
|
else:
|
|
raise TabularFileError('unknown format %r' % format)
|