-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert.py
More file actions
79 lines (57 loc) · 2.08 KB
/
Copy pathconvert.py
File metadata and controls
79 lines (57 loc) · 2.08 KB
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
77
78
79
# import csv
# import json
# # Function to convert a CSV to JSON
# # Takes the file paths as arguments
# def make_json(csvFilePath, jsonFilePath):
# # create a dictionary
# data = {}
# # Open a csv reader called DictReader
# with open(csvFilePath, encoding='utf-8') as csvf:
# csvReader = csv.DictReader(csvf)
# # Convert each row into a dictionary
# # and add it to data
# for rows in csvReader:
# # Assuming a column named 'No' to
# # be the primary key
# key = rows['No']
# data[key] = rows
# # Open a json writer, and use the json.dumps()
# # function to dump data
# with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
# jsonf.write(json.dumps(data, indent=4))
# # Driver Code
# # Decide the two file paths according to your
# # computer system
# csvFilePath = r'first_edit.csv'
# jsonFilePath = r'data.json'
# # Call the make_json function
# make_json(csvFilePath, jsonFilePath)
import csv
import json
file = 'crime_data2.csv'
json_file = 'outputcrime.json'
#Read CSV File
def read_CSV(file, json_file):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
field = reader.fieldnames
for row in reader:
csv_rows.extend([{field[i]:row[field[i]] for i in range(len(field))}])
convert_write_json(csv_rows, json_file)
#Convert csv data into json
def convert_write_json(data, json_file):
with open(json_file, "w") as f:
f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '))) #for pretty
f.write(json.dumps(data))
read_CSV(file,json_file)
# import pandas as pd
# import json
# filepath = "crime_data2.csv"
# output_path = "outputcrime.json"
# df = pd.read_csv(filepath)
# # Create a multiline json
# json_list = json.loads(df.to_json(orient = "records"))
# with open(output_path, 'w') as f:
# for item in json_list:
# f.write("%s\n" % item)