It is easy to create a CSV file using a spreadsheet (such as Excel) manually to create a lot of data with the same item. However, when I pass it to another tool, I sometimes have to use a JSON file, so I made a Python script to use in that case. I needed JSON-formatted data to run Python unittests in a data-driven manner.
Python unittest DDT > Example usage
OS : Windows Python : v3.5.1
The JSON file is indented so that it has a layout that is easy for people to read. When I put a Japanese comment, I didn't put it because an encoding error occurred in the json.dumps line at runtime. (I couldn't solve it myself, so I put it on hold. I wonder if all of Linux and Mac will not give an error in UTF-8.)
script.py
# -*- coding: utf-8 -*-
import csv
import json
import sys, os, codecs
argvs = sys.argv
for csv_file_path in argvs:
if csv_file_path == __file__:
continue
with codecs.open(csv_file_path, 'r', 'shift_jis') as f:
json_reader = csv.reader(f)
name, ext = os.path.splitext(os.path.basename(csv_file_path))
with codecs.open(name + '_datapool.json', 'w', 'shift_jis') as json_file:
out = json.dumps([line_json for i, line_json in enumerate(json_reader) if i > 0] ,ensure_ascii=False, indent=4, sort_keys=False, separators=(',', ': '))
json_file.write(out)
Execute the above script file with the csv file as an argument. (Multiple specifications allowed)
>python script.py csv_file1.csv
The JSON file example that is created is as follows.
csv_file1_datapool.json
[
[
"Test 1",
"Test 2"
],
[
"Tesuto 1",
"Street fighter 2"
]
]
Get the file name with an argument Python: Get command line arguments – sys.argv variable
Specify encoding to read / write the file Learning site from Python introduction to application-File reading and writing
Recommended Posts