学习文件储存时,尝试写一个可以实现暂时储存人名的json文件模拟一个数据库,需要open的可读写参数且不会覆盖原先内容。
查阅资料得知参数a+为a的可读模式且自顶部开始读取,代码如下:
import json
basefile = "name.json"
username = input("what is your name?:")
with open(basefile,'a+') as b_file:
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!")
执行结果却无法判断名字是否在文件中:
================= RESTART: C:\Users\28654\Desktop\idle可擦除脚本.py =================
what is your name?:Mike
Green hand,we will say hello to you next time!
>>>
================= RESTART: C:\Users\28654\Desktop\idle可擦除脚本.py =================
what is your name?:Mike
Green hand,we will say hello to you next time!
>>>
得知,a+模式光标被放在文本末尾,无论以哪种方式读取文件,都是以当前光标所在位置向下读取,故在读取前必须要用seek方法将光标移动到文件开头(以下参照另一位博主的介绍):
f.seek(offset,whence)有两个参数:
offset代表控制指针移动的字节数
whence:代表参照什么位置进行移动
whence=0: 参照文件开头(默认)
whence=1: 参照当前所在的位置,必须在二进制模式下使用
whence=2: 参照文件末尾,必须在二进制模式下使用
由此,改写新代码:
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!")
执行结果:
================= RESTART: C:\Users\28654\Desktop\idle可擦除脚本.py =================
what is your name?:Mike
Green hand,we will say hello to you next time!
>>>
================= RESTART: C:\Users\28654\Desktop\idle可擦除脚本.py =================
what is your name?:Mike
Hello Mike,welcome back!
但有一个问题未解决,json文件中储存的字符串是"Mike\n",也就是说转换符不明何故被转义了,已验证与rstrip无关,还请大佬说明原因。