这是我的代码;
locat_file = 'info/locat.txt'
Import os
If not os.path.exists(locat_file):
#Ask location
locat = raw_input("Where are you from?\n").title
with open(locat_file, "w") as f:
f.write(locat)
f.close
此代码效果很好。我使用相同的代码来存储名称。唯一的问题是如果你说我住在爱尔兰'或者'我的名字是bob'它会保存你的名字,因为我的名字是bob'当我只想保存鲍勃部分时?
答案 0 :(得分:0)
检查答案中是否有空格,尽管您可以执行更复杂的检查:
If not os.path.exists(locat_file):
#Ask location
while True: # keep asking question until you get an acceptable answer
locat = raw_input("Where are you from?\n").title #Synchronous function, will wait for return before code continues to be interpreted
if ' ' not in locat: # condition(s) the answer need to meet
break
else:
print("there are no spaces allowed in a name")
with open(locat_file, "w") as f:
f.write(locat)
f.close
或者,只是告诉用户只输入他们的名字而不输入任何其他内容,然后他们给你的是他们的名字