-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv2json.py
31 lines (26 loc) · 875 Bytes
/
csv2json.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import json
import sys
import csv
def parse_csv(input_file, column):
with open(input_file, 'r') as file:
reader = csv.reader(file, delimiter=',', quotechar='"')
rows = list(reader)
lines = []
for row in rows:
lines.append(row[column])
return lines
def write_output(output_file, lines):
with open(output_file, 'w', encoding='utf-8') as file:
file.write('{"reviews":[')
file.write(','.join('"{}"'.format(line.replace('"', '\\"')) for line in lines))
file.write(']}')
if __name__ == '__main__':
args = sys.argv[1:]
if len(args) >= 3:
input_file = args[0]
column = int(args[1])
output_file = args[2]
lines = parse_csv(input_file, column - 1)
write_output(output_file, lines)
else:
print('Usage: csv2json.py input_file column_number output_file')