import csv import json import sys import os def csv_to_json(csv_filepath, json_filepath): data = [] with open(csv_filepath, encoding='utf-8') as csvf: csv_reader = csv.DictReader(csvf) for row in csv_reader: data.append(row) with open(json_filepath, 'w', encoding='utf-8') as jsonf: jsonf.write(json.dumps(data, indent=4)) def json_to_csv(json_filepath, csv_filepath): with open(json_filepath, 'r', encoding='utf-8') as jsonf: data = json.load(jsonf) if data: with open(csv_filepath, 'w', encoding='utf-8', newline='') as csvf: writer = csv.DictWriter(csvf, fieldnames=data[0].keys()) writer.writeheader() writer.writerows(data) def auto_convert(input_file): file_name, file_extension = os.path.splitext(input_file) if file_extension.lower() == ".csv": output_file = f"{file_name}.json" csv_to_json(input_file, output_file) print(f"Converted {input_file} to {output_file}") elif file_extension.lower() == ".json": output_file = f"{file_name}.csv" json_to_csv(input_file, output_file) print(f"Converted {input_file} to {output_file}") else: print("Unsupported file format. Please provide a .csv or .json file.") sys.exit(1) if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: python convert.py ") sys.exit(1) input_file = sys.argv[1] auto_convert(input_file)