52 lines
No EOL
1.4 KiB
Python
52 lines
No EOL
1.4 KiB
Python
import csv
|
|
import json
|
|
import logging
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(message)s',
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def csv_to_json(csv_path: str, json_path: str) -> None:
|
|
try:
|
|
with open(csv_path) as file:
|
|
reader: csv.DictReader[str] = csv.DictReader(file)
|
|
result: list[dict[str, str]] = []
|
|
for row in reader:
|
|
if not reader.fieldnames:
|
|
raise IOError()
|
|
|
|
data: dict[str, str] = {}
|
|
|
|
for fieldname in reader.fieldnames:
|
|
data[fieldname] = row[fieldname]
|
|
|
|
result.append(data)
|
|
|
|
with open(json_path, 'w') as output_file:
|
|
json.dump(result, output_file, indent=2, ensure_ascii=False)
|
|
|
|
except FileNotFoundError:
|
|
logger.error("File not found")
|
|
except IOError:
|
|
logger.error("Cannot read csv file")
|
|
|
|
def json_to_csv(json_path: str, csv_path: str) -> None:
|
|
try:
|
|
with open(json_path) as file:
|
|
data: list[dict[str, str]] = json.load(file)
|
|
|
|
if not data:
|
|
logger.error("Cannot read json file")
|
|
if data:
|
|
with open(csv_path, 'w') as output:
|
|
writer= csv.DictWriter(output, fieldnames=data[0].keys())
|
|
writer.writeheader()
|
|
writer.writerows(data)
|
|
|
|
except FileNotFoundError:
|
|
logger.error("File not found")
|
|
|
|
json_to_csv('./test.json', './test2.csv') |