Skip to content

Commit

Permalink
[processing] use csv module for table writer
Browse files Browse the repository at this point in the history
  • Loading branch information
alexbruy committed Sep 6, 2013
1 parent 6689964 commit 4a6eec7
Showing 1 changed file with 42 additions and 18 deletions.
60 changes: 42 additions & 18 deletions python/plugins/processing/core/TableWriter.py
Expand Up @@ -23,29 +23,53 @@
# This will get replaced with a git SHA1 when you do a git archive # This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$' __revision__ = '$Format:%H$'


from qgis.core import * import csv

import codecs
from PyQt4.QtCore import * import cStringIO


class TableWriter: class TableWriter:

def __init__(self, fileName, encoding, fields): def __init__(self, fileName, encoding, fields):
self.fileName = fileName self.fileName = fileName
self.writer = None if not self.fileName.lower().endswith("csv"):
self.fileName += ".csv"


if encoding is None: self.encoding = encoding
settings = QSettings() if self.encoding is None or encoding == "System":
encoding = settings.value("/ProcessingQGIS/encoding", "System") self.encoding = "utf-8"


if not fileName.endswith("csv"): with open(self.fileName, "wb") as csvFile:
fileName += ".csv" self.writer = UnicodeWriter(csvFile, encoding=self.encoding)
file = open(fileName, "w") self.writer.writerow(fields)
file.write(";".join(unicode(field.name()) for field in fields))
file.write("\n")
file.close()


def addRecord(self, values): def addRecord(self, values):
file = open(self.fileName, "a") with open(self.fileName, "ab") as csvFile:
file.write(";".join([unicode(value) for value in values])) self.writer = UnicodeWriter(csvFile, encoding=self.encoding)
file.write("\n") self.writer.writerow(values)
file.close()
def addRecords(self, records):
with open(self.fileName, "ab") as csvFile:
self.writer = UnicodeWriter(csvFile, encoding=self.encoding)
self.writer.writerows(records)

class UnicodeWriter:
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()

def writerow(self, row):
row = map(unicode, row)
try:
self.writer.writerow([s.encode("utf-8") for s in row])
except:
self.writer.writerow(row)
data = self.queue.getvalue()
data = data.decode("utf-8")
data = self.encoder.encode(data)
self.stream.write(data)
self.queue.truncate(0)

def writerows(self, rows):
for row in rows:
self.writerow(row)

0 comments on commit 4a6eec7

Please sign in to comment.