I'm really a beginner. Why is it different from the printout when I save Python CSV?

Asked 2 weeks ago, Updated 2 weeks ago, 2 views

import boto3 import datetime import csv

boto_sts = boto3.client('sts') #assumes you have a default profile set accounts = ['3333', '2222', '1111']

for id in accounts: role_arn = f'arn:aws:iam::{id}:role/org-hmx-cloudop-operator-admin' role_session = f'dev-{id}-session' sts_response = boto_sts.assume_role(RoleArn=role_arn, RoleSessionName=role_session) creds = sts_response['Credentials'] #session = boto3.Session(aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken']) resource = boto3.client('ec2', aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken']) #ec2 = session.client('ec2') # # credential = f'AWS_SESSION_TOKEN={id}, AWS_ACCESS_KEY_ID={id}, AWS_SECRET_ACCESS_KEY={id}'.format( # # creds.credentials.session_token, # # creds.credentials.access_key, # # creds.credentials.secret_key # ) #print(result) result = resource.describe_instances( )
time = datetime.datetime.now().strftime ('%Y-%m-%d-%H-%M-%S') filename_describe_instances = ('hyundaigroup_aws_' + time + '.csv') fieldnames = ['Instance_Name','ImageId', 'InstanceId', 'InstanceType', 'Availability_Zone', 'Platform', 'PrivateIpAddress','PublicIpAddress', 'State', 'SubnetId','VpcId', 'Environment', 'AccountId', 'KeyName' ]

    with open(filename_describe_instances, 'w', newline='') as csvFile:
        writer = csv.writer(csvFile, delimiter=',')
        writer.writerow(fieldnames)
        for Reserv in result['Reservations']:
            for Insta in Reserv['Instances']:
                instance_imageid = Insta.get('ImageId', 'NULL')
                instance_InstanceId = Insta.get('InstanceId', 'NULL')
                instance_InstanceType = Insta.get('InstanceType', 'NULL')
                instance_Availability_Zone = Insta['Placement'].get('AvailabilityZone', 'NULL')
                instance_Platform = Insta.get('Platform', 'Linux')
                instance_Private_IP = Insta.get('PrivateIpAddress', 'NULL')
                instance_Public_IP = Insta.get('PublicIpAddress', 'NULL')
                instance_State = Insta['State'].get('Name', 'NULL')
                instance_Subnet = Insta.get('SubnetId', 'NULL')
                instance_VPCID = Insta.get('VpcId', 'NULL')
                instance_OwnerId = Reserv.get('OwnerId', 'NULL')
                instance_KeyName = Insta.get('KeyName', 'NULL')                    
                #tags_list = []
                #instance_Environment = 'NULL'           
                for n in Insta.get('Tags', 'NULL'):                    
                    if n.get('Key', 'NULL') == 'Name':
                        instance_Name = n.get('Value', 'NULL')                                        
                    #elif n.get('Key', 'NULL') == 'Environment':                        
                       #instance_Environment = n.get('Value', 'NULL')

                    raw = [
                        instance_Name,
                        instance_imageid,
                        instance_InstanceId,
                        instance_InstanceType,
                        instance_Availability_Zone,
                        instance_Platform,
                        instance_Private_IP,
                        instance_Public_IP,
                        instance_State,
                        instance_Subnet,
                        instance_VPCID,
                      #  #  instance_Environment,                
                        instance_OwnerId,
                        instance_KeyName
                        ]
                    print(raw)
#The results I want come out well here                      
                    writer.writerow(raw)
#Only the last Rooftaina group comes out here                                                                                                                                        

csvFile.close():

Why is the result different from the actual result of the last print shooting?


2022-09-20 15:17

1 Answers

It looked complicated, so I simply organized the above code


import csv

accounts = ['3333', '2222', '1111']
result = {}

for id in accounts:
    print('result')
    with open('hyundaigroup_aws.csv', 'w', newline='') as csvFile:
        writer = csv.writer(csvFile, delimiter=',')
        for Reserv in result['Reservations']:
            for Insta in Reserv['Instances']:
                for n in Insta.get('Tags', 'NULL'):
                    raw = [
                        Insta.get('a'),
                    ]
                    print(raw)
                    # The results I want come out well here
                    writer.writerow(raw)
                    # Only the last Roofta group is on here
    csvFile.close()

I think the last loop data you mentioned refers to the last data '1111' of accounts.

If you open the file in 'w' mode, the existing file will be erased (every time) and created anew. In the above question, a new file is created (the existing file is erased) for each id of accounts with a for statement and opened.

[em] Well, if you don't mean this, the answer below could be useless. But you asked me a question with such an ambiguous phrase. k

If it is because of this problem, change the write open mode to 'a' instead of 'w' and run it.

'a' is the Create (None) and Add (None) modes.


2022-09-20 15:17

If you have any answers or tips


© 2022 pinfo. All rights reserved.