Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a " AttributeError: '_io.TextIOWrapper' object has no attribute 'replace' " in python?

print (
"""    Welcome to the code breaker game!
       In this game you will have to change symbols into letters in order to decipher secret words. 
       0 - instructions
       1 - start
       2 - clues
       3 - check your answers
       4 - quit
""")

choice = input(" choice : ")

if choice == ("0"):
    text_file = open ("instructions.txt","r")
    print (text_file.read())
    text_file.close()

elif choice =="1":
    text_file = open ("words.txt","r")
    contents = text_file
    print (text_file.read())
    text_file.close()
    a = input("Please enter a symbol ")
    b = input("Please enter a letter ")

    newcontents = contents.replace(a,b)
    contents = newcontents
    print(contents,"\n")
    text_file.close


elif choice == "2":
 text_file = open ("clues.txt","r")
 print (text_file.read())
 text_file.close()

elif choice == "3":
 text_file = open ("solved.txt","r")
 print (text_file.read())
 text_file.close()

elif choice == "4":
 quit 

So basically I'm doing a computer science project and my task is to make a decoding game by substituting symbols to letters but I get this error for when I try to make the part of the code which actually changes symbols into letters.

Also is there any way to make this loop (not using while loops as they are quite complicated)? I basically want the code to show me the A and B when I run the program and for me after choosing any option to be able to choose a different option. (Eg I press 0 for instructions and then be able to choose a different option such as start game).

like image 452
user3661051 Avatar asked May 21 '14 13:05

user3661051


1 Answers

This part of your code:

text_file = open ("words.txt","r")
contents = text_file
print (text_file.read())
text_file.close()

makes no sense. You are assigning the file object (not the file's contents) to contents. You then print the contents, but don't assign them to anything. I think what you want is:

with open("words.txt") as text_file:
    contents = text_file.read()
print(contents)
like image 154
jonrsharpe Avatar answered Oct 22 '22 06:10

jonrsharpe