求大佬解答,问题再最后一行,如果我想用dump给文件追加内容该怎么办
'123'>>> # 我这里设置了三个变量
>>> a
123
>>> b
>>> b
>>> # 将a,b两个变量储存
>>> with open(r"E:\我python\test.txt","wb") as f:
pickle.dump((a,b),f)
>>> # 再拿出来是没问题的
>>> with open(r"E:\我python\test.txt","rb") as f:
pickle.load(f)
(123, )
>>> with open(r"E:\我python\test.txt","rb") as f:
pickle.load(f)
(123, )
>>> # 同样的运行两次,发现里面的数据不会因为拿出来而消失
>>> # 这时我想往里面追加变量c
>>> with open(r"E:\我python\test.txt","r+b") as f: # 采用的是r+b的二进制读写打开
pickle.dump(c,f)
>>> # 再次拿出来看看
>>> with open(r"E:\我python\test.txt","r+b") as f: # 还是二进制读写
pickle.load(f)
'123'
>>> # 晕,怎么变成只有变量c了,和单独的“w”打开出现的截断一样,求解答 >>> # 还是这三个变量
>>> a
123
>>> b
>>> c
'123'
>>> with open(r"E:\我python\test.txt","wb") as f:
pickle.dump((a,b),f)
>>> with open(r"E:\我python\test.txt","ab") as f: # 这次采用ab来打开,给文件追加c
pickle.dump(c,f)
>>> # 再把数据拿出来看看
>>> with open(r"E:\我python\test.txt","rb") as f:
pickle.load(f)
(123, )
>>> # 诶,变量c怎么不见了,又晕了,求解答 本帖最后由 jackz007 于 2022-10-30 20:19 编辑
pickle 的 dump 用于对对象的现场整体保存以及恢复,是一张现场快照,只适合一次性保存和使用,不适合追加以及做任何的加工和修改。
页:
[1]