debian-tablib/tablib/formats/_csv.py

56 lines
1.1 KiB
Python
Raw Normal View History

2010-09-25 11:49:21 +02:00
# -*- coding: utf-8 -*-
2010-09-25 22:49:21 +02:00
""" Tablib - CSV Support.
"""
2011-05-22 21:29:11 +02:00
from tablib.compat import is_py3, csv, StringIO
2010-09-25 11:49:21 +02:00
title = 'csv'
2012-06-08 09:10:43 +02:00
extensions = ('csv',)
2010-09-25 11:49:21 +02:00
DEFAULT_ENCODING = 'utf-8'
2010-09-25 11:49:21 +02:00
def export_set(dataset):
2011-02-17 22:31:52 +01:00
"""Returns CSV representation of Dataset."""
2011-05-22 21:29:11 +02:00
stream = StringIO()
if is_py3:
_csv = csv.writer(stream)
else:
_csv = csv.writer(stream, encoding=DEFAULT_ENCODING)
2010-09-25 11:49:21 +02:00
2011-02-17 22:31:52 +01:00
for row in dataset._package(dicts=False):
_csv.writerow(row)
2010-09-25 11:49:21 +02:00
2011-02-17 22:31:52 +01:00
return stream.getvalue()
2010-09-25 11:49:21 +02:00
def import_set(dset, in_stream, headers=True):
2011-02-17 22:31:52 +01:00
"""Returns dataset from CSV stream."""
2010-09-25 11:49:21 +02:00
2011-02-17 22:31:52 +01:00
dset.wipe()
2010-09-25 11:49:21 +02:00
if is_py3:
rows = csv.reader(in_stream.splitlines())
else:
rows = csv.reader(in_stream.splitlines(), encoding=DEFAULT_ENCODING)
2011-02-17 22:31:52 +01:00
for i, row in enumerate(rows):
2010-09-25 11:49:21 +02:00
2011-02-17 22:31:52 +01:00
if (i == 0) and (headers):
dset.headers = row
else:
dset.append(row)
2010-09-26 00:03:03 +02:00
def detect(stream):
2011-02-17 22:31:52 +01:00
"""Returns True if given stream is valid CSV."""
try:
2013-08-27 16:07:06 +02:00
csv.Sniffer().sniff(stream, delimiters=',')
2011-02-17 22:31:52 +01:00
return True
except (csv.Error, TypeError):
return False