JSON To CSV Python Code
import csv
import json
import os
def csv_to_json(csv_file_path, json_file_path):
try:
# Check if the CSV file exists
if not os.path.exists(csv_file_path):
print(f"The file {csv_file_path} does not exist.")
return
# Read the CSV data with 'latin1' encoding
data = []
with open(csv_file_path, mode='r', encoding='latin1') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
data.append(row)
# Write the JSON data
with open(json_file_path, mode='w', encoding='utf-8') as json_file:
json.dump(data, json_file, indent=4)
print(f"Successfully converted {csv_file_path} to {json_file_path}")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
csv_file_path = r'C:\Users\DOK Academy\Documents\Python Scripts\Customer.csv' # Use raw string literal
json_file_path = r'C:\Users\DOK Academy\Documents\Python Scripts\Customer.json' # Use raw string literal
csv_to_json(csv_file_path, json_file_path)