Python中“AttributeError: '_io.TextIOWrapper'对象没有'replace'属性”是什么意思?
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
基本上,我在做一个计算机科学项目,我的任务是制作一个解码游戏,通过把符号替换成字母来实现。但是当我尝试编写将符号转换成字母的代码时,出现了错误。
另外,有没有办法让这个循环(不使用while
循环,因为它们比较复杂)?我希望代码在运行时能显示A和B,然后我选择一个选项后,能够再选择一个不同的选项。(比如我按0查看说明,然后可以选择其他选项,比如开始游戏)。
1 个回答
9
你代码的这一部分:
text_file = open ("words.txt","r")
contents = text_file
print (text_file.read())
text_file.close()
是没有意义的。你把文件对象(而不是文件的内容)赋值给了 contents
。然后你用 print
打印了内容,但并没有把它们赋值给任何东西。我觉得你想要的是:
with open("words.txt") as text_file:
contents = text_file.read()
print(contents)