You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

csv_utils.py 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # -*- coding: utf-8 -*-
  2. import codecs
  3. import csv
  4. import cStringIO
  5. # These classes are copied from http://docs.python.org/2/library/csv.html
  6. class CsvUnicodeWriter(object):
  7. """
  8. A CSV writer which will write rows to CSV file "f",
  9. which is encoded in the given encoding.
  10. """
  11. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  12. # Redirect output to a queue
  13. self.queue = cStringIO.StringIO()
  14. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  15. self.stream = f
  16. self.encoder = codecs.getincrementalencoder(encoding)()
  17. def cast_to_str(self, obj):
  18. if isinstance(obj, unicode):
  19. return obj.encode('utf-8')
  20. elif isinstance(obj, str):
  21. return obj
  22. elif hasattr(obj, '__unicode__'):
  23. return unicode(obj).encode('utf-8')
  24. elif hasattr(obj, '__str__'):
  25. return str(obj)
  26. else:
  27. raise TypeError('Expecting unicode, str, or object castable'
  28. ' to unicode or string, got: %r' % type(obj))
  29. def writerow(self, row):
  30. self.writer.writerow([self.cast_to_str(s) for s in row])
  31. # Fetch UTF-8 output from the queue ...
  32. data = self.queue.getvalue()
  33. data = data.decode("utf-8")
  34. # ... and reencode it into the target encoding
  35. data = self.encoder.encode(data)
  36. # write to the target stream
  37. self.stream.write(data)
  38. # empty queue
  39. self.queue.truncate(0)
  40. def writerows(self, rows):
  41. for row in rows:
  42. self.writerow(row)
  43. class UTF8Recoder(object):
  44. """
  45. Iterator that reads an encoded stream and reencodes the input to UTF-8
  46. """
  47. def __init__(self, f, encoding):
  48. self.reader = codecs.getreader(encoding)(f)
  49. def __iter__(self):
  50. return self
  51. def next(self):
  52. return self.reader.next().encode("utf-8")
  53. class CsvUnicodeReader(object):
  54. """
  55. A CSV reader which will iterate over lines in the CSV file "f",
  56. which is encoded in the given encoding.
  57. """
  58. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwargs):
  59. f = UTF8Recoder(f, encoding)
  60. self.reader = csv.reader(f, dialect=dialect, **kwargs)
  61. def next(self):
  62. row = self.reader.next()
  63. return [unicode(s, "utf-8") for s in row]
  64. def __iter__(self):
  65. return self