Python - 将循环输出写入文件

时间:2017-12-15 22:05:20

标签: python

我能够以我想要的格式打印这个,如何将其写入文件?     导入json

#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()

1 个答案:

答案 0 :(得分: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