How to make python create a new excel file and store the data provided row by row. Any answer is appreciated, thank you

Question:

I want my code to create a new excel file called "OUTPUT_FILE" and store the provided data row by row but, the problem is that it is overwriting all the data to the 1st row.
This is how it is storing the data
This is how I want it to store the data

and here is my code:

y = 0
z = 0
for x in range(1, 10):
    y = y + x
    z = z + x
    Claim_Level = []
    
    Something_1 = x
    Something_2 = y
    Something_3 = z
    head = namedtuple('Inv', '''Something_1 Something_2 Something_3''')
    Claim_Level.append((head(x, y, z)))
    csvgenerater = pd.DataFrame(Claim_Level)
    
    with pd.ExcelWriter('OUTPUT_FILE.xlsx', engine='openpyxl', mode='w') as writer:
        csvgenerater.to_excel(writer, sheet_name='ClaimLevel_Output', index=False)
Asked By: Dev

||

Answers:

You just need to fix your indentation as follows:

from collections import namedtuple
from pandas import ExcelWriter, DataFrame

y = 0
z = 0
Claim_Level = []
head = namedtuple('Inv', '''Something_1 Something_2 Something_3''')

for x in range(1, 10):
    y = y+x
    z = z+x
    Claim_Level.append(head(x, y, z))

with ExcelWriter('OUTPUT_FILE.xlsx', engine='openpyxl', mode='w') as writer:
    DataFrame(Claim_Level).to_excel(writer, sheet_name='ClaimLevel_Output', index=False)

Note:

Also removed some redundant code

Answered By: DarkKnight
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.