看到另一位博主的问题,自己尝试多次未果,所以来请教一下。
遇到的问题时,最后追加新的username时,后面的换行符始终被识别为字符串一并添加,如何才能正确添加为换行符,使每次追加新的username时都是下一行
import json
basefile = "name.json"
username = input("what is your name?:")
with open(basefile,'a+') as b_file:
b_file.seek(0,0)
content = b_file.read()
if username in content:
print("Hello "+username+",welcome back!")
elif username not in content:
json.dump(username.rstrip()+"\n",b_file)
print("Green hand,we will say hello to you next time!")
在json.dump(username.rstrip()+"\n",b_file) 下面加一行代码 b_file.write("\n")单独加换行
json本身就一字典,你这换行追加一个字符串,以后怎么load?
真的要加换行,可以当做文本文件一样处理,在json.dump下一行加上 print("",file=b_file)