-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcsv-to-json.py
59 lines (42 loc) · 1.28 KB
/
csv-to-json.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
"""
Run this script in your local machine.
Ideally have one source file for each platform
Please ensure your source files are in this
comma-delimited format before continuing:
,,USR,PWD
1,user@example.com,password1
2,user2@example.com,password2
3,abc@xyz.com,password3
Outputs:
A text file containing a single JSON string in the format
{"user@example.com": "password1", "user2@example.com": "password2", "abc@xyz.com": "password3"}
for each platform
"""
from os import listdir
import json
from csv import DictReader
def find_csv_filenames(path_to_dir=".", suffix=".csv"):
filenames = listdir(path_to_dir)
return [filename for filename in filenames if filename.endswith(suffix)]
source_files = find_csv_filenames()
print(
f"""
>>> Will read from {source_files}"""
)
for source_file in source_files:
dest_file = f'{source_file.split(".")[0]}.txt'
cred_dict = {}
with open(source_file, mode="r") as csv_file:
reader = DictReader(csv_file)
for row in reader:
cred_dict[(row["USR"]).strip()] = row["PWD"].strip()
cred_str = json.dumps(cred_dict)
with open(dest_file, "w") as text_file:
text_file.write(cred_str)
print(
f"""
>>> Opening {source_file}...
>>> Written to {dest_file}:
{cred_str}
"""
)