2017-09-06 5 views
-1

次のコードは、 '.csv'ファイルを 'json'ファイルに変換するために使用します。変換中は辞書の各データ項目を文字列に変換します。データを整数に変換する方法行番号44はキーとデータを辞書に追加します。これは実際に辞書の辞書です。辞書は、あなたの混乱の質問のうち、このビットを爪弾く行番号53Pythonで辞書値の整数出力を取得する

import sys, getopt 
import csv 
import json 

#Get Command Line Arguments 
def main(argv): 
    input_file = '' 
    output_file = '' 
    format = '' 
    try: 
     opts, args = getopt.getopt(argv,"hi:o:f:",["ifile=","ofile=","format="]) 
    except getopt.GetoptError: 
     print('1062368.csv -i <path to inputfile> -o <path to outputfile> -f <dump/pretty>') 
     sys.exit(2) 
    for opt, arg in opts: 
     if opt == '-h': 
      print('1062368.csv -i <path to inputfile> -o <path to outputfile> -f <dump/pretty>') 
      sys.exit() 
     elif opt in ("-i", "--ifile"): 
      input_file = arg 
     elif opt in ("-o", "--ofile"): 
      output_file = arg 
     elif opt in ("-f", "--format"): 
      format = arg 
    print(output_file) 
    read_csv(input_file, output_file, format) 

#Read CSV File 
def read_csv(file, json_file, format): 
    csv_rows = {} 
    with open(file) as csvfile: 
     reader = csv.DictReader(csvfile) 
     title = reader.fieldnames 
     #print(len(title)) = 4 
     n = 0 
     p = 0 
     month = 1 
     day = 1 
     file_name = 2000 
     csv_rows[month] = {} 
     #the following loop runs the number of rows times i.e. 6412 
     for row in reader: 
      csv_rows[month][day] = {} 
      csv_rows[month][day] = {title[i]:row[title[i]] for i in range(len(title))} 
      day = day + 1 
      if day == 30: 
       day = 1 
       month = month + 1 
       csv_rows[month] = {} 
      n = n+1 
      if n == 365: 
       temp_file = (str)(file_name+p) 
       write_json(csv_rows, temp_file+'.json', format) 
       n = 0 
       p = p+1 
       csv_rows={} 
       month = 1 
       day = 1 
       csv_rows[month] = {} 
     #write_json(csv_rows, json_file, format) 

#Convert csv data into json and write it 
def write_json(data, json_file, format): 
    with open(json_file, "w") as f: 
     if format == "pretty": 
      f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '),encoding="utf-8",ensure_ascii=False)) 
     else: 
      f.write(json.dumps(data)) 

if __name__ == "__main__": 
    main(sys.argv[1:]) 
+1

クールです。あなたの質問は何ですか?これは基本的にコードのダンプです。 – blacksite

+1

文字列を整数に変換する方法を知りたければ、その文字列をすべてポストする必要はありませんでした。 –

答えて

1

でJSONファイルに書き込まれます。

方法は、データが整数に変換取得する

int()を使用してください。

string_value = '5' 
int_value = int(string_value) 
+0

intをstrに変換しようとしているときに、 'ValueError'例外をキャッチしようとすると、 – blacksite

+1

@blacksite一度に1つのこと。 :-) –

関連する問題