CSVExporter.py 1.71 KB
Newer Older
1 2
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
3
from .Exporter import Exporter
4 5 6 7 8 9 10 11 12 13 14 15 16
from pyqtgraph.parametertree import Parameter


__all__ = ['CSVExporter']
    
    
class CSVExporter(Exporter):
    Name = "CSV from plot data"
    windows = []
    def __init__(self, item):
        Exporter.__init__(self, item)
        self.params = Parameter(name='params', type='group', children=[
            {'name': 'separator', 'type': 'list', 'value': 'comma', 'values': ['comma', 'tab']},
17
            {'name': 'precision', 'type': 'int', 'value': 10, 'limits': [0, None]},
18 19 20 21 22 23 24 25
        ])
        
    def parameters(self):
        return self.params
    
    def export(self, fileName=None):
        
        if not isinstance(self.item, pg.PlotItem):
Luke Campagnola's avatar
Luke Campagnola committed
26
            raise Exception("Must have a PlotItem selected for CSV export.")
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
        
        if fileName is None:
            self.fileSaveDialog(filter=["*.csv", "*.tsv"])
            return

        fd = open(fileName, 'w')
        data = []
        header = []
        for c in self.item.curves:
            data.append(c.getData())
            header.extend(['x', 'y'])

        if self.params['separator'] == 'comma':
            sep = ','
        else:
            sep = '\t'
            
        fd.write(sep.join(header) + '\n')
        i = 0
46 47 48
        numFormat = '%%0.%dg' % self.params['precision']
        numRows = reduce(max, [len(d[0]) for d in data])
        for i in range(numRows):
49 50
            for d in data:
                if i < len(d[0]):
51
                    fd.write(numFormat % d[0][i] + sep + numFormat % d[1][i] + sep)
52 53 54 55 56 57 58 59
                else:
                    fd.write(' %s %s' % (sep, sep))
            fd.write('\n')
        fd.close()