python 文件读取

# coding:utf-8
from collections import OrderedDict
import pickle
import json

history = {}
list_value = ["1", "2", "a"]
dict_all = dict([("test", list_value)])
#二进制加载 读取
try:
    history = pickle.load(open(r"1234.txt", "rb"))
except:
    # 创建
    with open(r"1234.txt",'w'):
        pass

# 更新字典
history.update(dict_all)
# 二进制写入字典
pickle.dump(history, open(r"1234.txt", "wb"))



"""
'r':读
'w':写
'a':追加
'r+' == r+w(可读可写,文件若不存在就报错(IOError))
'w+' == w+r(可读可写,文件若不存在就创建)
'a+' ==a+r(可追加可写,文件若不存在就创建)
对应的,如果是二进制文件,就都加一个b就好啦:
'rb'  'wb'  'ab'  'rb+'  'wb+'  'ab+'
"""

#
# # 普通
# try:
#     # 读取
#     with open(r"12.txt", 'r') as f:
#         # 转换为dict
#         history = json.loads(f.read())
# except:
#     # 创建
#     with open(r"12.txt",'w'):
#         pass
# or
with open(r'134.txt','w+') as f:
    try:
        history = json.loads(f.read())
    except:
        pass
    
history.update(dict_all)

# 最后写入
with open(r"134.txt", 'w+') as f:
    # 写入只能是str
    f.write(json.dumps(history))
    # f.write("hello,world")
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容