普通文件读写
# 文件写入 info = { "name": "Tom", "age": 23 } f = open("info.txt", "w") f.write(str(info)) # {'name': 'Tom', 'age': 23} f.close() # 文件读取 f = open("info.txt", "r") data = eval(f.read()) f.close() print(type(data), data) # <class 'dict'> {'name': 'Tom', 'age': 23}
通过json
import json # 序列化,只能一次 f = open("info2.txt", "w") json.dump(info, f) #相当于 f.write(json.dumps(info)) # {"name": "Tom", "age": 23} f.close() # 反序列化,只能一次 f = open("info2.txt", "r") data = json.load(f) #相当于: data = json.loads(f.read()) f.close() print(type(data), data) # <class 'dict'> {'name': 'Tom', 'age': 23}
如果需要有乱码
或者需要美观缩进对齐
,可以使用如下方式进行格式化输出:
with open("result.txt", "w") as f: txt = json.dumps(lst, ensure_ascii=False, indent=4) f.write(txt)
参考: python json.dumps()函数输出json格式,使用indent参数对json数据格式化输出
通过pickle
try: import cPickle as pickle # c语言,读写更快 except ImportError: import pickle # 写入 def sayHi(): print("Hello world!") info = { "name": "Tom", "age": 23, "func": sayHi } f = open("info3.txt", "wb") f.write(pickle.dumps(info)) # 等价于:pickle.dump(info, f) f.close() """ �}q (X funcqc__main__ sayHi qX ageqKX nameqX Tomqu. """ # 读取 f = open("info3.txt", "rb") data = pickle.loads(f.read()) # 等价于:pickle.load(f) f.close() print(type(data),data) # <class 'dict'> {'name': 'Tom', 'func': <function sayHi at 0x0000000002E5CBF8>, 'age': 23} data["func"]() # 调用 Hello world!