【问题标题】:Function works correctly only the first time it is called [duplicate]函数仅在第一次调用时才能正常工作[重复]
【发布时间】:2016-11-08 12:05:36
【问题描述】:

我有以下功能,第二个功能count_forbid(a)只能工作1次。在此示例中,它计算不包含字母 'c' 的单词的正确值,但对于 y,它返回零。所以这意味着代码只能在第一次正确执行,而在所有其他时间返回零:

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')

【问题讨论】:

    标签: python function file python-3.x


    【解决方案1】:

    在你遍历文件之后:

        for line in fin:
    

    它会走到尽头,尝试重新迭代将没有效果。

    要么更改函数以使用context manager,在调用函数时重新打开文件:

    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
    

    这是在 python 中打开文件的首选方式。

    或者,在您的调用之间添加 fin.seek(0) 以使文件指向开头:

    x = count_forbid('c')
    fin.seek(0)
    y = count_forbid('d')
    

    【讨论】:

    • 您也可以“手动”打开和关闭文件,而不是使用上下文管理器。
    • 当然,但这取决于您保持警惕并始终记得关闭它的事实。这就是为什么上下文管理器是一个很好的构造,它们为你做这件事,让你担心更重要的事情:-)。
    • 哇,超级有效,非常感谢。
    • @AnhHoang 如果这解决了您的问题,您可以通过单击答案旁边的勾号将其标记为已接受的答案:-)
    • @Jim 我标记了它,谢谢,我只是一个新手第一次使用stackoverflow,非常抱歉延迟滴答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多