Today, a little blind spot when do reptiles: strings, dictionaries, write to the same file. Difficult to use!
Such data such as:
STR =. "Hi, I like Budy 52pojie!"
Dirt = { "Chen Mo": [ "M", "22"]}
a, saved to a file txt
1
2
3
|
with
open
(
"text.txt"
,
"w"
) as f: f.write(
str
)
#write()只能保存string
f.write(
str
(dirt))
|
So read it out, how to read are strings. dirt is difficult to use.
Second, the data saved to json, using the json.load and json.dump
1
2
|
with
open
(
"a.json"
,
"w"
) as f: json.dump(
str
,f)
json.dump(dirt,f)
|
Json use when reading. the dump (), this produces an error, a string, a dictionary is. Reading together data types is not uniform.
Then read separately, which is a third way:
three ,, json.load and json.dump + json.loads () use
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import
json
def
read_json():
with
open
(
"a.json"
,
"r"
) as f:
#每一行为一个列表的元素,各行独立
data
=
f.readlines()
for
dat
in
data:
#去掉行后的空白,换行或者回车
dat
=
dat.rstrip()
#利用json.loads()恢复每一行的保存前数据类型,
dir
=
json.loads(dat)
#打印数据类型
print
(
type
(
dir
))
print
(
dir
)
def
write_json():
with
open
(
"a.json"
,
"w"
) as f:
str
=
[
1
,
2
,
5
,
3
,
4
,
5
]
json.dump(
str
,f)
#每行后换行,保证每条数据相互独立。
f.write(
"\n"
)
str
=
{
11
:
22
,
33
:
44
}
json.dump(
str
,f)
f.write(
"\n"
)
str
=
"hello budy!"
json.dump(
str
,f)
#这样会产生比较多的空间浪费。每行有可能不到一半,
if
__name__
=
=
"__main__"
:
write_json()
read_json()
|
In doing so, to my current level, a lot of convenience, the saved data can easily follow his original data type to use. However, a lot of wasted space is generated,
such as line 100 bytes, probably with 10 bytes