Python:为什么我的程序忘记了用户对文本文件的输入?

时间:2018-02-07 17:22:35

标签: python python-3.x text-files

这可能听起来有点令人困惑,但我正在尝试创建一个程序,可以向用户询问名称,将该输入存储在文本文件中,然后检查将来的用户输入以查看该名称是否在文件中

我让它适用于一次运行,即输入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

1 个答案:

答案 0 :(得分:0)

id读取结尾换行符,但输入的名称没有换行符。替换:

readlines()

使用:

if HeroName in open("HeroHolder2.txt", "r+").readlines():
    print(HeroName + ", is in database")