Python开发Hangman游戏遇AttributeError: 'int'对象无readline属性
问题排查与解决方法
错误原因
- 默认参数类型错误:
load_words函数默认参数设为inFile=0,调用时没传参数,导致inFile是整数类型,而整数没有readline()方法,直接触发AttributeError。 - 文件对象未绑定:代码里执行了
open('words.txt', 'r')但没把返回的文件对象赋值给inFile,等于白打开文件,后续还是用默认的整数0调用方法,自然报错。
修复后的代码
直接简化函数逻辑,正确处理文件读取:
import random import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") # 用with语句打开文件,自动处理关闭操作 with open(WORDLIST_FILENAME, 'r') as inFile: line = inFile.readline() words = line.split() print(" ", len(words), "words loaded.") return words # 调用函数加载词表 wordlist = load_words()
如果需要保留函数的灵活性(比如支持传入已打开的文件对象),可以改成:
def load_words(inFile=None): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. :param inFile: 可选文件对象,未传入时默认读取WORDLIST_FILENAME """ print("Loading word list from file...") # 未传入文件对象时,打开默认文件 if inFile is None: inFile = open(WORDLIST_FILENAME, 'r') line = inFile.readline() words = line.split() print(" ", len(words), "words loaded.") # 仅关闭函数内部打开的文件,外部传入的由调用者负责关闭 if inFile is not None and inFile.name == WORDLIST_FILENAME: inFile.close() return words
关键修改说明
- 移除了错误的整数默认参数,直接在函数内部处理文件打开逻辑,避免类型错误。
- 使用
with语句管理文件,确保文件使用后自动关闭,防止资源泄漏。 - 把
open的返回值绑定到inFile变量,保证后续能正常调用文件对象的方法。
内容的提问来源于stack exchange,提问作者Many Dog
相关产品推荐
相关产品推荐

