0

I have the following function, the second function count_forbid(a) can only work 1 time. In this example it count the right value of the word that do not contain letter 'c', but for y it return zero. So it means the code can only do right first time and for all other time it return zero:

import string
fin = open('words.txt')
def forbid_or_not(word,forb):
    for letter in word:
        if letter in forb:
            return False
    return True

def count_forbid(a):
    count = 0
    for line in fin:
        word1 = line.strip()
        if forbid_or_not(word1,a):
            count += 1
    return count

x = count_forbid('c')
y = count_forbid('d')
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Anh Hoang
  • 79
  • 8

1 Answers1

4

After you iterate through the file with:

    for line in fin:

it is going to reach the end and trying to re-iterate will have no effect.

Either change the function to use a context manager that re-opens the file when the function is called:

def count_forbid(a):
    count = 0
    with open('words.txt') as fin:  # closes the file automatically
        for line in fin:
            word1 = line.strip()
            if forbid_or_not(word1,a):
                count += 1
    return count

which is the preferred way of opening files in python.

Or, add fin.seek(0) in between your calls in order to get the file to point to the beginning:

x = count_forbid('c')
fin.seek(0)
y = count_forbid('d')
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • Instead of using the context manager you can also just "manually" open and close the file. – syntonym Jul 06 '16 at 12:47
  • 1
    Of course, but that relies on the fact that you're vigilant and always remember to close it. That's why context managers are such a nice construct, they do that for you and let you worry about more important things :-). – Dimitris Fasarakis Hilliard Jul 06 '16 at 12:50
  • WOW, super effective, thank a lot. – Anh Hoang Jul 06 '16 at 13:13
  • @AnhHoang if this solved your issue you can mark it as the accepted answer by clicking on the tick mark next to the answer :-) – Dimitris Fasarakis Hilliard Jul 06 '16 at 13:18
  • @Jim True, and one should use the context managers, but the wording implied to me that using a context manager or using seek are the only options available. I think it's important to understand that a context manager is only "syntactic sugar" and does not anything that couldn't be achieved otherwise. – syntonym Jul 06 '16 at 13:40
  • 1
    @Jim I marked it, thanks, I am just a newbie first time use stackoverflow so very sorry for the delay tick. – Anh Hoang Jul 10 '16 at 11:11