<s> from __future__ import unicode_literals <EOL> import csv <EOL> from datetime import datetime , date <EOL> from six import PY3 , text_type <EOL> from dataset . freeze . format . common import Serializer <EOL> def value_to_str ( value ) : <EOL> if isinstance ( value , ( date , datetime ) ) : <EOL> return text_type ( value . isoformat ( ) ) <EOL> if not PY3 and hasattr ( value , '<STR_LIT>' ) : <EOL> return value . encode ( '<STR_LIT:utf-8>' ) <EOL> if value is None : <EOL> return '<STR_LIT>' <EOL> return value <EOL> class CSVSerializer ( Serializer ) : <EOL> def init ( self ) : <EOL> self . handles = { } <EOL> def write ( self , path , result ) : <EOL> keys = list ( result . keys ( ) ) <EOL> if path not in self . handles : <EOL> if path is not None : <EOL> if PY3 : <EOL> fh = open ( path , '<STR_LIT>' , encoding = '<STR_LIT:utf8>' , newline = '<STR_LIT>' ) <EOL> else : <EOL> fh = open ( path , '<STR_LIT:wb>' ) <EOL> else : <EOL> fh = self . fileobj <EOL> writer = csv . writer ( fh ) <EOL> if PY3 : <EOL> writer . writerow ( keys ) <EOL> else : <EOL> writer . writerow ( [ value_to_str ( k ) for k in keys ] ) <EOL> self . handles [ path ] = ( writer , fh ) <EOL> writer , fh = self . handles [ path ] <EOL> values = [ value_to_str ( result . get ( k ) ) for k in keys ] <EOL> writer . writerow ( values ) <EOL> def close ( self ) : <EOL> for writer , fh in self . handles . values ( ) : <EOL> if fh != self . fileobj : <EOL> fh . close ( ) </s>
