Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

AttributeError: 'int' object has no attribute 'readline'

I am trying to make a hangman game in python but i get the attribute error in my title. this is my code

enter image description here

I have no idea what might be causing this attribute error in my code. I think it might have something to do with my code not having the correct naming or it might be how i defined in-File

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import random
import string


WORDLIST_FILENAME = "words.txt"


def load_words(inFile=0):
    """
    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:
    """
    
    print("Loading word list from file...")
    # inFile: file
    open('words.txt', 'r')

    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    words = line.split()
    print("  ", len(words), "words loaded.")
    return words

Error:

File "C:)Users\ ManyDog\ PycharmProjects\ hangman\main.py", line 49, in <module>
    wordlist = load_words ()
File "C:)Users\ ManyDog\PycharmProjects\hangman\main.py", line 27, in Load_words
    line = inFile. readline ()
AttributeError: 'int' object has no attribute 'readline'

>Solution :

You default inFile to an int but then try to use it as a file object. Internal to the function, you open a file but since you don’t use its returned file object, it is immediately closed.

Instead, read the opened file. In this example, I’ve used your hard coded file name as a default for the function.

def load_words(inFile="words.txt"):
    """
    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:
    """
    
    print("Loading word list from file...")
    # inFile: file
    with open(inFile) as fileObj:
        # line: string
        line = fileObj.readline()
    words = line.split()
    print("  ", len(words), "words loaded.")
    return words
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading