I have a csv file ('data_counter_1.csv') which looks like below:
N;52201261;EM3000v2;2.0;20210801000000;20210801010000;20210801010000;51.28983;15.22345;172.19.224.70;0.0.0.0;ns;
C;20210801000500;127;51.28984;15.22344;127;0;0000000000000;3880356.4*kWh;978928.9*kWh;127;0.6*kWh;0.0*kWh;127;
C;20210801001000;127;51.28984;15.22345;127;0;0000000000000;3880357.0*kWh;978928.9*kWh;127;0.6*kWh;0.0*kWh;127;
C;20210801001500;127;51.28984;15.22344;127;0;0000000000000;3880357.6*kWh;978928.9*kWh;127;0.6*kWh;0.0*kWh;127;
C;20210801002000;127;51.28984;15.22344;127;0;0000000000000;3880358.2*kWh;978928.9*kWh;127;0.6*kWh;0.0*kWh;127;
I want specific values from csv file export to excel; one value from (let's say) N-row will be the first value for rows created with specific C-rows values. I wrote a code in pyhton (below), which I thought one should have dealt with this simple task. Unfortunately, while running script I get error: "if row[0] == 'N': IndexError: list index out of range" or "if row[0] == 'C': IndexError: list index out of range" if I modify the code a little.
I've tried to deal with this for a couple of days so I would be grateful for help or at least a tip. Much thanks in advance for Your time.
My code:
import csv
from openpyxl import Workbook
workbook = Workbook()
worksheet = workbook.active
with open('data_counter_1.csv', 'r') as file:
reader = csv.reader(file, delimiter=';')
for row in reader:
if row[0] == 'N':
const_value = row[1]
elif row[0] == 'C':
row_data = [const_value, row[1], row[8], row[9], row[3], row[4]]
worksheet.append(row_data)
workbook.save('output_counter_1.xlsx')
I would be grateful for help or at least a tip. Much thanks in advance for Your time.
rowvariable? Just between theforstatement and theif-elifstatement.row[0] is out of indexthat would meanrowis an empty list.rowthat doesn't exist. Add a conditional that ensuresrowisn't empty prior checking the N-, and C-row.if row:above the if-elif section, but it's context dependent what works (better).)