-1

I'm rather new to programming, so please forgive me if it's a dumb question, but I honestly spent at least 2 hours looking for a way do my task, which seems fairly simple, but I haven't succeeded.

I have a temp folder in which there is a csv file. I need to read the file and then divide elements from sublists into separate lists. When I check what the file looks like inside, I get content of such a format:

['category', 'text']

There are multiple lists like that. I have extract 'category' to a separate list labels, and 'text' to sentences.

I tried something like this:

for item in csvfile:
   labels.append(item[0])
   sentences.append(item[1])

Unfortunately I get an error that index is out of range. When I searched for indices for elements in nested lists I only found complicated functions that assign indices to elements first, only then I can call them.

Do you guys know easier solution to this problem?

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

Given a CSV file that looks like this:

name, year, grade
Adam, 3, A 
Bob, 2, B
Chuck, 1, C 

The code to extract each column into a separate list might look like this:

import csv

names = []
years = []
grades = []

with open('students.csv') as csv_file:
    students = csv.reader(csv_file, delimiter=',')
    lines = 0
    for student in students:
        if lines > 0: # ignore first line - column heading
            names.append(student[0])
            years.append(student[1])
            grades.append(student[2])
        lines += 1
    
print(names)
Adam Oellermann
  • 303
  • 1
  • 7