2017-12-15 22 views
-2

これを私が望む形式で印刷することができます。どのようにファイルに書き込むのですか? 輸入JSONPython - ループ出力をファイルに書き込む

#myfile = open('us-west-2-offering-script.txt', 'w') 

with open('Pricing_Json_Cli.json', 'r') as f: 
    rawData = json.load(f) 

for each in rawData['ReservedInstancesOfferings']: 
    print('PDX', ',' 
      , each['InstanceType'], ',' 
      , each['InstanceTenancy'], ',' 
      , each['ProductDescription'], ',' 
      , each['OfferingType'], ',' 
      , each['Duration'], ',' 
      , each['ReservedInstancesOfferingId'], ',' 
      , each['FixedPrice'], ',', end='' 
     ) 
    if not each['RecurringCharges']: 
     print("0.0") 
    else: 
     print(each['RecurringCharges'][0].get('Amount')) 

myfile.close()

答えて

2

あなたがprint()機能のための出力ストリームを定義することができますが、よりストレートな方法は、だけではなく、file_stream.write()を使用することです:

with open("output_file", "w") as f: # open output_file for writing 
    for each in rawData['ReservedInstancesOfferings']: 
     # join all elements by a comma and write to the file 
     f.write(",".join(
      map(str, ("PDX", 
         each['InstanceType'], 
         each['InstanceTenancy'], 
         each['ProductDescription'], 
         each['OfferingType'], 
         each['Duration'], 
         each['ReservedInstancesOfferingId'], 
         each['FixedPrice'], 
         "0.0" if not each['RecurringCharges'] 
         else each['RecurringCharges'][0].get('Amount'))) 
     )) 
     f.write("\n") # write a new line at the end 
+0

実際の違いは、最後に改行を無料で取得するかどうかだけです。 –

+0

素晴らしいです、ありがとうございます。私は一歩近づいていると思うが、['RecurringCharges'] [0] .get( 'Amount')はintであり、結合は文字列を探すためにこのエラーが出る。 私はstr()ですべてのものをラップしようとしましたが、うまくいきません。思考? –

+0

@Ka_Fari - アップデートを確認してください。 – zwer

関連する問題