1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python3でCSVからJSONへ変換する

Last updated at Posted at 2021-09-07

Python3を使用して、CSVファイルをJSONファイルに変換します。

実行方法

$ python3 csv2json.py -i <入力CSVファイル> -o <出力JSONファイル> --delimiter ',' --header-only 0
オプション
-i 入力CSVファイル
-o 出力JSONファイル
--delimiter CSV区切り文字
--header-only 0: データも含めて出力したい, 1: ヘッダのみを出力したい

コード

csv2json.py
import csv
import json
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', help='Input file name (CSV)', required=True)
parser.add_argument('-o', '--output', help='Output file name (JSON)', required=True)
parser.add_argument('--delimiter', help='Input CSV Delimiter')
parser.add_argument('--header-only', type=int, help='Output only header (Exclude data) 0:True/1:False', choices=[0,1])
args = parser.parse_args()
 
input_file = args.input
output_file = args.output
 
header_only = 0
if args.header_only in globals():
    header_only = args.header_only
 
csv_delimiter = ','
if args.delimiter in globals():
    csv_delimiter = args.delimiter
 
print("Input File:" + input_file)
print("Output File:" + output_file)
 
 
result = []
f_input_file = open(input_file, "r")
if header_only == 1:
    data = csv.reader(f_input_file, delimiter=csv_delimiter, doublequote=True, quotechar='"', skipinitialspace=True)
    for row in data:
        for col in row:
            result.append(col)
        break
 
 
else:
    data = csv.DictReader(f_input_file, delimiter=csv_delimiter, doublequote=True, quotechar='"', skipinitialspace=True)
 
    for row in data:
        result.append(row)
 
f_output_file = open(output_file, "w")
f_output_file = json.dump(result, f_output_file, indent=2, ensure_ascii=False)
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?