'Indexing a multiple characters from a csv file

I am attempting to index specific characters to their own variable, and I am only able to do this for 1 character.

with open(fileName) as f:
    count1 = sum(l[0] == '1' for l in f)
    count2 = sum(l[0] == '2' for l in f)

print(count1)
print(count2)

This is my output

5 0

According to the values in the csv file, it should be:

5 4

I should mention, when I change the value from '1' to '2' in the first variable, it does give me 4, for some reason I cannot do both though.



Solution 1:[1]

Well, once you've iterated over f once, f is exhausted. That is, reading from it will return nothing.

There are basically 2 ways to fix this:

1: open the file twice

with open(fileName) as f:
    count1 = sum(l[0] == '1' for l in f)
with open(fileName) as f:
    count2 = sum(l[0] == '2' for l in f)

2: read the file into memory and use that

with open(fileName) as f:
    lines = f.readlines()

count1 = sum(l[0] == '1' for l in lines)
count2 = sum(l[0] == '2' for l in lines)

Which of the two you use is up to you.

(code is untested. might contain typos)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sören