Home > database >  How do I fix the Open function not working as expected in Python?
How do I fix the Open function not working as expected in Python?

Time:09-03

I'm trying to do some sort of hangman game, and after googling how to open a file, this was the consensus of how to achieve that:

WordFile = open("HangmanWords.txt", "r")
Axe = WordFile.read()
WordList = Axe.split("\n")
print(WordList)
print(Axe)
print(WordFile)
WordFile.close()

But when I do this, the output came up like this:

['']

<_io.TextIOWrapper name='HangmanWords.txt' mode='r' encoding='cp1252'>

The list is blank, "Axe" is as well, and the open() command spits out that, I'm not the most experienced with coding, but I'm doing most of this to get better. Does anyone know how to troubleshoot this?

CodePudding user response:

I copied the code into pycharm, created a txt file that has

hang
man
words

in it, and it works for me. It prints:

['hang', 'man', 'words']
hang
man
words
<_io.TextIOWrapper name='HangmanWords.txt' mode='r' encoding='cp1250'>

What do you have in the file?

CodePudding user response:

It appears as though you are trying to open a file and read words from that file into a list. If this is the case, then the convention would be to do this:

with open('HangmanWords.txt', 'r') as f:
    axe = f.read()

wordlist = axe.split('\n')

print(wordlist)

The with statement opens and (guaranteed) closes the file once the code block is executed.

  • Related