python之open参数w+、a+等模式无法读取数据的问题

学习文件储存时,尝试写一个可以实现暂时储存人名的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无关,还请大佬说明原因。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值