python 文件读取
2018-07-17 本文已影响22人
你常不走的路
# 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")