我正在创建一个聊天机器人,如果UserName.txt文件不存在,用户要做的第一件事就是输入他们的姓名和喜欢,但是输入的文本不会保存。我在做什么错?
我尝试删除UserLike函数以查看是否有区别,但这似乎不起作用
def NameSay():
UserName = input(": ")
UserNameFile = open("UserName.txt", "w+")
UserNameFile.write(UserName)
print("So your name is "+ UserName + ", right?")
NameConfirm = input(": ")
if 'yes' in NameConfirm or 'Yes' in NameConfirm or 'right' in NameConfirm or 'Right' in NameConfirm or 'ya' in NameConfirm or 'Ya' in NameConfirm or 'yeah' in NameConfirm or 'Yeah' in NameConfirm:
print("Good to meet you, " + UserName + ". I'm Ene, your virtual assistant, friend, coworker, whatever you need me to be!")
print("Now, why don't you tell me a bit about yourself? What you like and all of that.")
UserLike = input(": ")
UserLikesFile = open("UserLikes.txt", "w")
UserLikesFile.write(UserLike)
print("Thank you! This is very interesting info.")
if NameConfirm in ['no', 'No']:
print("Oh? Then tell me what your name is.")
NameSay()
if os.path.isfile('UserName.txt') == True:
f = open("UserName.txt", "r")
file_contents = f.read()
welcomes = ["Welcome back, " + file_contents, "Hey-o! Good to see you again, " + file_contents]
print("\n" + welcomes[random.randint(0,1)])
Main_Menu()
if os.path.isfile('UserName.txt') == False:
print("\nHey-o! I don't think we've met before! What\'s your name?")
NameSay()
文本应保存到书面文件中,但文件最终为空白。
为了安全起见,可以在写入功能之后立即将输出刷新到文件。
UserNameFile.flush()
也请不要忘记关闭文件
UserNameFile.close()
我刚刚运行了此命令,但数据确实保存了,所以我不太确定您的意思。但是,我可以看到您在按需使用文件后没有关闭文件。
您的代码有两个问题,我认为:
1-打开文件时,应关闭或刷新该文件以能够读取该文件
2-您正在递归调用NameSay()
,并且如果某人输入错误的用户名10次,则您的函数调用堆栈应保存所有这些。因此,我编辑了没有递归调用该函数的最后一行代码,并编辑了NameSay
函数以返回True
或False
,以确定是否成功
def NameSay():
UserName = input(": ")
with open("UserName.txt", "w+") as UserNameFile:
UserNameFile.write(UserName)
print("So your name is "+ UserName + ", right?")
NameConfirm = input(": ")
if 'yes' in NameConfirm or 'Yes' in NameConfirm or 'right' in NameConfirm or 'Right' in NameConfirm or 'ya' in NameConfirm or 'Ya' in NameConfirm or 'yeah' in NameConfirm or 'Yeah' in NameConfirm:
print("Good to meet you, " + UserName + ". I'm Ene, your virtual assistant, friend, coworker, whatever you need me to be!")
print("Now, why don't you tell me a bit about yourself? What you like and all of that.")
UserLike = input(": ")
with open("UserLikes.txt", "w") as UserLikesFile:
UserLikesFile.write(UserLike)
print("Thank you! This is very interesting info.")
return True
if NameConfirm in ['no', 'No']:
print("Oh? Then tell me what your name is.")
return False
if os.path.isfile('UserName.txt') == True:
f = open("UserName.txt", "r")
file_contents = f.read()
welcomes = ["Welcome back, " + file_contents, "Hey-o! Good to see you again, " + file_contents]
print("\n" + welcomes[random.randint(0,1)])
Main_Menu()
if os.path.isfile('UserName.txt') == False:
print("\nHey-o! I don't think we've met before! What\'s your name?")
while(not NameSay())
continue