user3058889
user3058889

Reputation: 79

Read file and separate to different lists

below is my CSV dataset.

a,d,g

b,e,h

c,f,i

I would like to separate these 3 column as row[0], row[1], and row[2]. And also to make them as 3 different lists.

Here is my code:

import csv

file1 = open('....my_path.csv')


Row_0 = [row[0].upper() for row in csv.reader(file1)]
Row_1 = [row[1].upper() for row in csv.reader(file1)]
Row_2 = [row[2].upper() for row in csv.reader(file1)]

print Row_0
print Row_1
print Row_2

However, I only can see Row_0 result from the console. But the Row_1 and Row_2 are always showing [ ]. Which means I only can see the first row, but not the second and following rows.

['A', 'B', 'C']
[]
[]

Does anyone can help me to deal with this "simple" issue?

Upvotes: 2

Views: 57

Answers (2)

user2555451
user2555451

Reputation:

open returns an iterator, which becomes exhausted (no longer usable) after you iterate through it once. Moreover, each time you do csv.reader(file1), csv.reader will try to iterate over the iterator referenced by file1. This means that, after the first call, this iterator will become exhausted and all subsequent calls to csv.reader will be using an empty iterator.

To do what you want, you would need something like:

import csv

file1 = open('....my_path.csv')


Row_0, Row_1, Row_2 = ([row[0].upper(), row[1].upper(), [row[2].upper()]
                       for row in csv.reader(file1))

print Row_0
print Row_1
print Row_2

Now, we get all of the data in one read and only iterate over the iterator once.

Also, in case you are wondering, the code I used is known as a generator expression. You could also use a list comprehension:

Row_0, Row_1, Row_2 = [[row[0].upper(), row[1].upper(), [row[2].upper()]
                       for row in csv.reader(file1)]

but I don't see a point in building a list just to throw it away.

Upvotes: 3

dm03514
dm03514

Reputation: 55942

You've read through the whole file! check out the file position after your first comprehension,

You could seek(0) between comprehensions or just iterate once, or reopen the file as @kdopen stated

Upvotes: 0

Related Questions