Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

csv_utils.py 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. # Write BOM into file
  18. self.stream.write(codecs.BOM_UTF8)
  19. def writerow(self, row):
  20. self.writer.writerow([unicode(s).encode("utf-8") for s in row])
  21. # Fetch UTF-8 output from the queue ...
  22. data = self.queue.getvalue()
  23. data = data.decode("utf-8")
  24. # ... and reencode it into the target encoding
  25. data = self.encoder.encode(data)
  26. # write to the target stream
  27. self.stream.write(data)
  28. # empty queue
  29. self.queue.truncate(0)
  30. def writerows(self, rows):
  31. for row in rows:
  32. self.writerow(row)
  33. class UTF8Recoder(object):
  34. """
  35. Iterator that reads an encoded stream and reencodes the input to UTF-8
  36. """
  37. def __init__(self, f, encoding):
  38. self.reader = codecs.getreader(encoding)(f)
  39. def __iter__(self):
  40. return self
  41. def next(self):
  42. return self.reader.next().encode("utf-8")
  43. class CsvUnicodeReader(object):
  44. """
  45. A CSV reader which will iterate over lines in the CSV file "f",
  46. which is encoded in the given encoding.
  47. """
  48. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwargs):
  49. f = UTF8Recoder(f, encoding)
  50. self.reader = csv.reader(f, dialect=dialect, **kwargs)
  51. def next(self):
  52. row = self.reader.next()
  53. return [unicode(s, "utf-8") for s in row]
  54. def __iter__(self):
  55. return self