Python3 write to excel with loops

Question:

I’ve spent an entire week trying to write to excel in the following format:

Name  Model  Serial  Version
name1 model1 serial1 version1
name2 model2 serial2 version2
name3 model3 serial3 version3

I’ve tried lists, loops, enummerate, zip. I know its a silly logic problem that I’m doing, but I have no one to point it out to me.

No matter how many mods I do to my code, I end up rewriting the output over the rows or columns, or writing duplicates.

I’m running API calls to a list of devices, then iterating through the result to find the interesting tags and then printing the text of those tags into an excel.

Asked By: JR21

||

Answers:

using pandas:

import pandas as pd

lines = 3

df = pd.DataFrame([[f'name{i}', f'model{i}', f'serial{i}', f'version{i}'] for i in range(1, lines + 1)],
                  columns=['Name', 'Model', 'Serial', 'Version'])

df.to_excel("myfile.xlsx", index=None)

enter image description here

Answered By: Ze'ev Ben-Tsvi

thank you. I was able to solve it differently:

from xlwt import Workbook
sheet1 = wb.add_sheet('Sheet 1',cell_overwrite_ok=True)
list_of_tags=['hostname','model','serial','sw-version']
for row,host in enumerate(file):
     <API calls to host>
     for tag in list_of_tags:
        for child in root_sys.iter('*'):
            if (child.tag == tag):
                sys_info.append(child.text)
    for col in range(len(sys_info)):
       sheet1.write(row+1,col,sys_info[col])
Answered By: JR21
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.