writer.writerow () не пишет в правильный столбец - PullRequest
0 голосов
/ 06 декабря 2018

У меня есть три DynamoDB таблицы.Две таблицы имеют идентификаторы экземпляров, которые являются частью приложения, а другая является основной таблицей всех экземпляров всех моих учетных записей и метаданных тега.У меня есть два сканирования для двух таблиц, чтобы получить идентификаторы экземпляра, а затем запросить в основной таблице метаданные тега.Однако, когда я пытаюсь записать это в файл CSV, я хочу иметь два отдельных раздела заголовка для уникального вывода каждой таблицы динамо.Как только первая итерация завершена, запись второго файла записывается в последнюю строку, где первая итерация прервана, вместо того, чтобы начинать с начала во втором разделе заголовка.Ниже мой код и пример вывода, чтобы прояснить это.

CODE:

import boto3
import csv
import json 
from boto3.dynamodb.conditions import Key, Attr

dynamo = boto3.client('dynamodb')
dynamodb = boto3.resource('dynamodb')
s3 = boto3.resource('s3')

# Required resource and client calls
all_instances_table = dynamodb.Table('Master')
missing_response = dynamo.scan(TableName='T1')
installed_response = dynamo.scan(TableName='T2')

# Creates CSV DictWriter object and fieldnames 
with open('file.csv', 'w') as csvfile:
    fieldnames = ['Agent Not Installed', 'Not Installed Account', 'Not Installed Tags', 'Not Installed Environment', " ", 'Agent Installed', 'Installed Account', 'Installed Tags', 'Installed Environment']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    # Find instances IDs from the missing table in the master table to pull tag metadata 
    for instances in missing_response['Items']:
        instance_missing = instances['missing_instances']['S']
        #print("Missing:" + instance_missing)
        query_missing = all_instances_table.query(KeyConditionExpression=Key('ID').eq(instance_missing))

        for item_missing in query_missing['Items']:
            missing_id = item_missing['ID']
            missing_account = item_missing['Account']
            missing_tags = item_missing['Tags']
            missing_env = item_missing['Environment']
            # Write the data to the CSV file
            writer.writerow({'Agent Not Installed': missing_id, 'Not Installed Account': missing_account, 'Not Installed Tags': missing_tags, 'Not Installed Environment': missing_env})

    # Find instances IDs from the installed table in the master table to pull tag metadata
    for instances in installed_response['Items']:
        instance_installed = instances['installed_instances']['S']
        #print("Installed:" + instance_installed)
        query_installed = all_instances_table.query(KeyConditionExpression=Key('ID').eq(instance_installed))

        for item_installed in query_installed['Items']:
            installed_id = item_installed['ID']
            print(installed_id)
            installed_account = item_installed['Account']
            installed_tags = item_installed['Tags']
            installed_env = item_installed['Environment']

            # Write the data to the CSV file 
            writer.writerow({'Agent Installed': installed_id, 'Installed Account': installed_account, 'Installed Tags': installed_tags, 'Installed Environment': installed_env})

OUTPUT:

Так выглядят столбцы / строки в файле.enter image description here

Мне нужно, чтобы все выходные данные были в одной строке для каждого раздела заголовка.

DATA:

Вот пример того, как выглядят обе таблицы.

enter image description here enter image description here

SAMPLE OUTPUT:

Вот что печатает цикл for и добавляет к спискам.

Отсутствует:

i-0xxxxxx 333333333 foo@bar.com int 
i-0yyyyyy 333333333 foo1@bar.com int

Установлено:

i-0zzzzzz 44444444 foo2@bar.com int
i-0aaaaaa 44444444 foo3@bar.com int

1 Ответ

0 голосов
/ 06 декабря 2018

Вы хотите собрать связанные строки в один список для записи в одну строку, что-то вроде:

missing = [] # collection for missing_responses
installed = [] # collection for installed_responses

# Find instances IDs from the missing table in the master table to pull tag metadata 
for instances in missing_response['Items']:
    instance_missing = instances['missing_instances']['S']
    #print("Missing:" + instance_missing)
    query_missing = all_instances_table.query(KeyConditionExpression=Key('ID').eq(instance_missing))
    for item_missing in query_missing['Items']:
        missing_id = item_missing['ID']
        missing_account = item_missing['Account']
        missing_tags = item_missing['Tags']
        missing_env = item_missing['Environment']
        # Update first half of row with missing list
        missing.append(missing_id, missing_account, missing_tags, missing_env)

# Find instances IDs from the installed table in the master table to pull tag metadata
for instances in installed_response['Items']:
    instance_installed = instances['installed_instances']['S']
    #print("Installed:" + instance_installed)
    query_installed = all_instances_table.query(KeyConditionExpression=Key('ID').eq(instance_installed))

    for item_installed in query_installed['Items']:
        installed_id = item_installed['ID']
        print(installed_id)
        installed_account = item_installed['Account']
        installed_tags = item_installed['Tags']
        installed_env = item_installed['Environment']
        # update second half of row by updating installed list
        installed.append(installed_id, installed_account, installed_tags, installed_env)
# combine your two lists outside a loop
this_row = []
i = 0;
for m in missing:
    # iterate through the first half to concatenate with the second half
    this_row.append( m + installed[i] )
    i = i +1

# adding an empty column after the write operation, manually, is optional
# Write the data to the CSV file 
writer.writerow(this_row)

Это будет работать, если ваши установленные и отсутствующие таблицы работают в соответствующем поле - например,отметка времени или идентификатор учетной записи, то, что вы можете гарантировать, сохраняет строки в одном и том же порядке.Выборка данных была бы полезна, чтобы действительно ответить на вопрос.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...