-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv2list.py
executable file
·76 lines (60 loc) · 1.52 KB
/
csv2list.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env python3
"""
csv2list.py
hjltu@ya.ru
29-jul19
task: csv to list
usage:
./csv2list.py my.csv
"""
import sys
import csv
def check_csv_to_not_ascii(csvfile):
return
isascii = lambda s: len(s) == len(s.encode())
with open(csvfile, 'r') as f:
data = f.read()
return isascii(data)
def remove_whitespaces_from_list(row):
out = []
for r in row:
l = r.replace(' ','')
ll = l.replace("\\",'')
out.append(ll)
return out
def read_csv(csvfile):
try:
with open(csvfile, newline='', encoding='utf-8') as f:
reader = csv.reader(f, delimiter=',')
return csv_to_list_of_dicts(reader)
except:
return "ERR read csv's"
def csv_to_list_of_dicts(reader):
l=[]
line=0
d={}
for row in reader:
if row:
row = remove_whitespaces_from_list(row)
if '#' not in row[0]:
if line is 0:
col = row
else:
try:
d = dict(zip(col, row))
d["acc"] = d["sys"] + '_' + d["type"] + str(line)
l.append(d)
except:
print('ERR:', row)
line += 1
print(l)
return l
def main(csvfile):
if check_csv_to_not_ascii(csvfile) is False:
return "ERR not ascii string"
return read_csv(csvfile)
if __name__ == "__main__":
try:
main(sys.argv[1])
except Exception as e:
print(e)