这可能听起来有点令人困惑,但我正在尝试创建一个程序,可以向用户询问名称,将该输入存储在文本文件中,然后检查将来的用户输入以查看该名称是否在文件中
我让它适用于一次运行,即输入1名称,并且可以检查该名称是否在文件中。
但是,当我尝试使用其他名称时,它会完全忘记'关于名字。 有任何想法吗?谢谢 (提供的代码,文件和输出)
代码:
HeroName = ""
while HeroName != "Quit":
Hero = open("HeroHolder2.txt", "r+")
HeroName = input("Name a hero: ").title()
if HeroName in open("HeroHolder2.txt", "r+").readlines(): #checks to see if input is in file already
print(HeroName + ", is in database")
elif "Quit" in HeroName:
Hero.close()
quit()
elif "Clearholder" in HeroName: #makes the file new again
Hero = open("HeroHolder2.txt", "w")
print("Handbook cleared")
else: #Writes name to file if not already there
with open("HeroHolder2.txt", "a+") as Hero:
print("Hero invalid - adding to data base")
Hero.write("\n"+HeroName)
输出: Output to Shell
文字档案: What the text file shows
答案 0 :(得分:0)
id
读取结尾换行符,但输入的名称没有换行符。替换:
readlines()
使用:
if HeroName in open("HeroHolder2.txt", "r+").readlines():
print(HeroName + ", is in database")