Home > OS >  List generated from csv.reader not looping
List generated from csv.reader not looping

Time:12-09

New to python, so open to any suggestions of simplicity, pep, modules, etc.

Trying to create a script that can search for a value in a csv, (in this case grab the header fields) then index those values as variables. I'm able to grab the header from the ​CSV, but I can't get the list to loop through those values. Yes, I can create a second loop inside the original loop, but that's not the expected behavior. What am I missing?

import csv

data = [['SKU', 'Color', 'Delivery', 'Angles'], ['A1234', 'Red', 'Week 1', 'On-model, Pinup'], ['B4321', 'Black', 'Week 2', 'On-model'], ['JJ4567', 'Blue-Multi', 'Week 1', 'Pinup'], ['ClassicTee', 'Pink', 'Week 3', 'On-model, Pinup, Detail']]

with open('SKU_test3.csv', 'w') as csv_file_write:
   ​csv_writer = csv.writer(csv_file_write, delimiter=',')
   ​for row in data:
       ​csv_writer.writerow(row)

with open('SKU_test3.csv', 'r ') as csv_file_append:
   ​csv_reader = csv.reader(csv_file_append, delimiter = ',')
   ​header_names = []
   ​for row in csv_reader:
       ​header_names.append(row)
       ​break

print(type(header_names)) # returns: <class 'list'>

for i in header_names:
   ​print(i) # returns: ['SKU', 'Color', 'Delivery', 'Angles']

for j in i:
    print(j) # returns items as expected, but why is a nested loop needed?

CodePudding user response:

You're nesting the list of headers inside the header_names list. You should just assign it directly instead of using append().

with open('SKU_test3.csv', 'r ') as csv_file_append:
   ​csv_reader = csv.reader(csv_file_append, delimiter = ',')
   ​header_names = next(csv_reader)

If you just want the first element of a generator, you can use next() rather than a single iteration of a loop.

  • Related