python中存取对象类型的数据(json库)

从文件中读取数据是以字符串的形式读取的,同时,将数据写入文件中也是以字符串的形式写入,但如果写入一个对象(列表,字典等)则会报错。

file = open("file", "w")
data = ["a", "b"]
file.write(data)

以下是代码输出结果:

TypeError: write() argument must be str, not list

如果希望将一个对象类型的数据写入到文件中,则需要将其进行序列化(按照某种规则将内存中的数据转化为字节序列保存到文件中,相反则是反序列化),json库里面提供的dump()和dumps()方法可以将对象进行序列化。

import json

file = open("file", "w")
data = ["a", "b"]
print(type(data))
data = json.dumps(data)
file.write(data)
print(type(data))

以下是代码的输出结果:


而dump()方法可以在将对象序列化的同时将数据存储到指定的文件中。

import json

file = open("file", "w")
data = ["a", "b"]
json.dump(data, file)

同样的,使用json库中的load()和loads()方法可以将文件中的对象反序列化(将文件中的字符串转化为原来的对象数据)。

import json

file = open("file", "r")
text = file.read()
print(text)
print(type(text))
text = json.loads(text)
print(type(text))

以下是代码的输出结果:

["a", "b"]

其中,loads()方法需要先将文件读取再反序列化,而load()方法则不需要。

import json

file = open("file", "r")
text = json.load(file)
print(text)

以下是代码的输出结果:

['a', 'b']

该文章主要用来记录作者在学习python时遇到的问题及解决办法,如果有误请各位批评指正!

你可能感兴趣的:(json库函数,json,python)