简体   繁体   中英

How to update the existing csv file with values with comma separated files using python

I have the code to fetch the details from AWS Console, I have a CSV file with key and values. where the key is already written. Now I am trying to store the values generated during runtime in CSV next to comma separated key.

my python code:

import boto3
instance_count=[]
region = 'USA'
conn = boto3.resource('ec2', aws_access_key_id=access_key, 
aws_secret_access_key=secret_key,region_name=region)
instances= conn.instances.filter(Filters=[{'Name': 'instance-state-name', 
Values': ['running', 'stopped']}])
for instance in instances:
   instance_count.append(instance)
   instanceCount = str(len(instance_count))
   print('Instance count ->' + str(len(instance_count)))
   ##output: Instance count ->4 

but i need to store in same csv as below:

My csv be like :

    Param_Name,Param_Value
    p_instance_count,

Now I want to store the count (Eg: 4) that gets printed in cmd prompt inside csv next to p_instance_count,4

How can I do it?

import boto3
import csv

f = csv.writer(open("instance_count.csv", "a+"), lineterminator="\n")
instance_count=[]
region = 'us-east-1'
conn = boto3.resource('ec2', aws_access_key_id=access_key,
aws_secret_access_key=secret_key,region_name=region)
instances= conn.instances.filter(Filters=[{'Name': 'instance-state-name',
'Values': ['running', 'stopped']}])
for instance in instances:
    instance_count.append(instance)
    instanceCount = str(len(instance_count))
    print('Instance count ->' + str(len(instance_count)))
    ##output: Instance count ->4
f.writerow(('p_instance_count', len(instance_count)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM