정말 초보입니다... 파이썬 CSV 저장 하는데 왜 프린트 결과물과 실제 저장되는게 다를까요 ㅠㅠ

조회수 749회

import boto3 import datetime import csv

boto_sts = boto3.client('sts')

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' ]

print(result)

    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)
#여기선 제가 원하는 결과물이 잘나와요                      
                    writer.writerow(raw)
#여기선 마지막 루프테이타 그룹만나와요                                                                                                                                        

csvFile.close():

마지막 프린트 찍었을때 결과물과 실제 csv찍히는 결과가 왜 다를까요 ...

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 복잡해보여서 간단하게 위 코드를 정리해 보니

    
    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)
                        # 여기선 제가 원하는 결과물이 잘나와요
                        writer.writerow(raw)
                        # 여기선 마지막 루프테이타 그룹만나와요
        csvFile.close()
    
    

    언급하신 마지막 루프데이터accounts 의 마지막 데이터 '1111'을 말하는 것이라 생각됩니다.

    File을 'w' 모드 로 open 하면 (그때마다) 기존 File은 지워지고 새롭게 생성하게 됩니다. 위 질문에서는 for문으로 accounts의 각 id 마다 (기존 파일이 지워지고) 새롭게 파일을 생성해서 open 되게 됩니다.

    음.. 이런 의미가 아니셨으면 아래 답변은 쓸모없어질 수도 있겠군요.. 근데 워낙 애매한 문구로 질문 주셔서.. ㅋ

    혹시 이 문제 때문이라면, write open 모드를 'w' 가 아닌 'a' 모드로 바꿔서 실행해보세요.

    'a'는 (없으면) 생성 및 (있으면) 추가 모드입니다.

    • 아, 그리고 `with open` 문을 사용하시면 굳이 `file.close()` 안하셔도 됩니다. whistler7899 2021.8.15 11:42

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)