Skip to content

Commit 5c832a1

Browse files
authored
Merge pull request #8 from janrain/topic/JANRAIN-5916/add-delimiter-to-csv
topic/JANRAIN-5916/add-delimiter-to-csv
2 parents 93372c8 + 83504a4 commit 5c832a1

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

janrain_datalib/utils.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def to_json(item, compact=False):
2828
kwargs['separators'] = (',', ': ')
2929
return json.dumps(item, **kwargs)
3030

31-
def to_csv(row):
31+
def to_csv(row, delimiter=None):
3232
"""Convert a list of items to a CSV string.
3333
3434
Example:
@@ -37,6 +37,7 @@ def to_csv(row):
3737
3838
Args:
3939
row: list of items to be formatted as CSV
40+
delim: the delimiter to use for the CSV output
4041
4142
Returns:
4243
CSV record string
@@ -54,7 +55,14 @@ def to_csv(row):
5455
item = to_json(item, compact=True)
5556
new_row.append(item)
5657
output = io.StringIO()
57-
writer = csv.writer(output)
58+
59+
# if the delimiter is set use it
60+
if delimiter:
61+
writer = csv.writer(output, delimiter=delimiter)
62+
# otherwise use the default comma delimiter
63+
else:
64+
writer = csv.writer(output)
65+
5866
writer.writerow(new_row)
5967
return output.getvalue()
6068

tests/test_utils.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import unittest
2+
from janrain_datalib.utils import to_csv
3+
4+
class TestUtils(unittest.TestCase):
5+
6+
def test_to_csv_with_no_delimiter(self):
7+
# setup
8+
input = ['first', '2nd,with,commas', 'lasty']
9+
expected = 'first,"2nd,with,commas",lasty\r\n'
10+
# call
11+
result = to_csv(input)
12+
# test
13+
self.assertEqual(result, expected)
14+
15+
def test_to_csv_with_None_as_delimiter(self):
16+
# setup
17+
input = ['first', '2nd,with,commas', 'lasty']
18+
expected = 'first,"2nd,with,commas",lasty\r\n'
19+
delimiter = None
20+
# call
21+
result = to_csv(input, delimiter=delimiter)
22+
# test
23+
self.assertEqual(result, expected)
24+
25+
def test_to_csv_with_bar_delimiter(self):
26+
# setup
27+
input = ['first', '2nd,with,commas', 'lasty']
28+
expected = 'first|2nd,with,commas|lasty\r\n'
29+
delimiter = '|'
30+
# call
31+
result = to_csv(input, delimiter=delimiter)
32+
# test
33+
self.assertEqual(result, expected)
34+
35+
def test_to_csv_with_semicolon_delimiter(self):
36+
# setup
37+
input = ['first', '2nd,with,commas', 'lasty']
38+
expected = 'first;2nd,with,commas;lasty\r\n'
39+
delimiter = ';'
40+
# call
41+
result = to_csv(input, delimiter=delimiter)
42+
# test
43+
self.assertEqual(result, expected)

0 commit comments

Comments
 (0)