diff --git a/pyqtgraph/exporters/CSVExporter.py b/pyqtgraph/exporters/CSVExporter.py index b0cf5af5..6ed4cf07 100644 --- a/pyqtgraph/exporters/CSVExporter.py +++ b/pyqtgraph/exporters/CSVExporter.py @@ -52,10 +52,11 @@ class CSVExporter(Exporter): numRows = max([len(d[0]) for d in data]) for i in range(numRows): for d in data: - if i < len(d[0]): - fd.write(numFormat % d[0][i] + sep + numFormat % d[1][i] + sep) - else: - fd.write(' %s %s' % (sep, sep)) + for j in [0, 1]: + if i < len(d[j]): + fd.write(numFormat % d[j][i] + sep) + else: + fd.write(' %s' % sep) fd.write('\n') fd.close() diff --git a/pyqtgraph/exporters/tests/test_csv.py b/pyqtgraph/exporters/tests/test_csv.py new file mode 100644 index 00000000..70c69c72 --- /dev/null +++ b/pyqtgraph/exporters/tests/test_csv.py @@ -0,0 +1,49 @@ +""" +SVG export test +""" +import pyqtgraph as pg +import pyqtgraph.exporters +import csv + +app = pg.mkQApp() + +def approxeq(a, b): + return (a-b) <= ((a + b) * 1e-6) + +def test_CSVExporter(): + plt = pg.plot() + y1 = [1,3,2,3,1,6,9,8,4,2] + plt.plot(y=y1, name='myPlot') + + y2 = [3,4,6,1,2,4,2,3,5,3,5,1,3] + x2 = pg.np.linspace(0, 1.0, len(y2)) + plt.plot(x=x2, y=y2) + + y3 = [1,5,2,3,4,6,1,2,4,2,3,5,3] + x3 = pg.np.linspace(0, 1.0, len(y3)+1) + plt.plot(x=x3, y=y3, stepMode=True) + + ex = pg.exporters.CSVExporter(plt.plotItem) + ex.export(fileName='test.csv') + + r = csv.reader(open('test.csv', 'r')) + lines = [line for line in r] + header = lines.pop(0) + assert header == ['myPlot_x', 'myPlot_y', 'x', 'y', 'x', 'y'] + + i = 0 + for vals in lines: + vals = list(map(str.strip, vals)) + assert (i >= len(y1) and vals[0] == '') or approxeq(float(vals[0]), i) + assert (i >= len(y1) and vals[1] == '') or approxeq(float(vals[1]), y1[i]) + + assert (i >= len(x2) and vals[2] == '') or approxeq(float(vals[2]), x2[i]) + assert (i >= len(y2) and vals[3] == '') or approxeq(float(vals[3]), y2[i]) + + assert (i >= len(x3) and vals[4] == '') or approxeq(float(vals[4]), x3[i]) + assert (i >= len(y3) and vals[5] == '') or approxeq(float(vals[5]), y3[i]) + i += 1 + +if __name__ == '__main__': + test_CSVExporter() + \ No newline at end of file