什么是“ AttributeError: '_io.TextIOWrapper' object has no attribute 'replace' ”在python中?

use*_*051 5 python attributes

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 
Run Code Online (Sandbox Code Playgroud)

所以基本上我正在做一个计算机科学项目,我的任务是通过将符号替换为字母来制作解码游戏,但是当我尝试制作实际将符号更改为字母的代码部分时,我收到了这个错误。

还有什么方法可以使这个循环(不使用while循环,因为它们非常复杂)?我基本上希望代码在我运行程序时向我显示 A 和 B,并且在选择任何选项之后我可以选择不同的选项。(例如,我按 0 获取说明,然后可以选择不同的选项,例如开始游戏)。

jon*_*rpe 7

这部分代码:

text_file = open ("words.txt","r")
contents = text_file
print (text_file.read())
text_file.close()
Run Code Online (Sandbox Code Playgroud)

没有意义。您正在将文件对象(不是文件的内容)分配给contents. 然后print是内容,但不要将它们分配给任何东西。我想你想要的是:

with open("words.txt") as text_file:
    contents = text_file.read()
print(contents)
Run Code Online (Sandbox Code Playgroud)