python - Function works correctly only the first time it is called -
this question has answer here:
i have following function, second function count_forbid(a)
can work 1 time. in example count right value of word not contain letter 'c'
, y
return zero. means code can right first time , other time return zero:
import string fin = open('words.txt') def forbid_or_not(word,forb): letter in word: if letter in forb: return false return true def count_forbid(a): count = 0 line in fin: word1 = line.strip() if forbid_or_not(word1,a): count += 1 return count x = count_forbid('c') y = count_forbid('d')
after iterate through file with:
line in fin:
it going reach end , trying re-iterate have no effect.
either change function use context manager re-opens file when function called:
def count_forbid(a): count = 0 open('words.txt') fin: # closes file automatically line in fin: word1 = line.strip() if forbid_or_not(word1,a): count += 1 return count
which preferred way of opening files in python.
or, add fin.seek(0)
in between calls in order file point beginning:
x = count_forbid('c') fin.seek(0) y = count_forbid('d')
Comments
Post a Comment