I would like to count the occurences of missings of every line in a txt file.
foo.txt file:
1 1 1 1 1 NA # so, Missings: 1
1 1 1 NA 1 1 # so, Missings: 1
1 1 NA 1 1 NA # so, Missings: 2
But I would also like to obtain the amount of elements for the first line (assuming this is equal for all lines).
miss = []
with open("foo.txt") as f:
for line in f:
miss.append(line.count("NA"))
>>> miss
[1, 1, 2] # correct
The problem is when I try to identify the amount of elements. I did this with the following code:
miss = []
with open("foo.txt") as f:
first_line = f.readline()
elements = first_line.count(" ") # given that values are separated by space
for line in f:
miss.append(line.count("NA"))
>>> (elements + 1)
6 # True, this is correct
>>> miss
[1,2] # misses the first item due to readline() removing lines.`
How can I read the first line once without removing it for the further operation?
for line in f: ... elements = len(line.split()).