---for test---json
1 f = open("mall.txt",'w+',encoding='utf-8') 2 goods = { 3 '電子產品':[ 4 ['mac',7500,7], 5 ['iphone7',5400,5], 6 ['thunder',7600,3] 7 ], 8 '母嬰用品':[ 9 ['幫寶適',45.9,50], 10 ['美素佳兒',380,10] 11 ], 12 '摩托汽車':[ 13 ['特斯拉',820000,2], 14 ['雷克薩斯Rx450',450000,5] 15 ], 16 '平常用品':[ 17 ['東北大米',38.5,20], 18 ['上海青',3.6,47] 19 ] 20 } 21 s = str(goods) 22 f.write(s) 23 f.close()
1 with open("mall.txt",'r',encoding="utf-8") as f: 2 k = f.read() 3 f.close() 4 print(k)
1、用eval函數:app
1 s = eval(k) 2 3 print(type(s)) 4 for i in s: 5 print(i,s[i])
2、用json函數:(可是必須注意的是,json格式要求的是雙引號,單引號的話會報錯【選中單引號 --> ctrl + shift + alt + j --> 替換單引號爲雙引號】)iphone
1 print(json.loads(goods))
若是是單引號報錯內容:ide
1 print(json.loads(k)) 2 File "F:\Python35\lib\json\__init__.py", line 319, in loads 3 return _default_decoder.decode(s) 4 File "F:\Python35\lib\json\decoder.py", line 339, in decode 5 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 6 File "F:\Python35\lib\json\decoder.py", line 355, in raw_decode 7 obj, end = self.scan_once(s, idx) 8 json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
---恢復內容結束---函數
for test :spa
1 f = open("mall.txt",'w+',encoding='utf-8') 2 goods = { 3 '電子產品':[ 4 ['mac',7500,7], 5 ['iphone7',5400,5], 6 ['thunder',7600,3] 7 ], 8 '母嬰用品':[ 9 ['幫寶適',45.9,50], 10 ['美素佳兒',380,10] 11 ], 12 '摩托汽車':[ 13 ['特斯拉',820000,2], 14 ['雷克薩斯Rx450',450000,5] 15 ], 16 '平常用品':[ 17 ['東北大米',38.5,20], 18 ['上海青',3.6,47] 19 ] 20 } 21 s = str(goods) 22 f.write(s) 23 f.close()
1 with open("mall.txt",'r',encoding="utf-8") as f: 2 k = f.read() 3 f.close() 4 print(k)
1、用eval函數:3d
1 s = eval(k) 2 3 print(type(s)) 4 for i in s: 5 print(i,s[i])
2、用json函數:(可是必須注意的是,json格式要求的是雙引號,單引號的話會報錯【選中單引號 --> ctrl + shift + alt + j --> 替換單引號爲雙引號】)code
1 print(json.loads(goods))
若是是單引號報錯內容:blog
1 print(json.loads(k)) 2 File "F:\Python35\lib\json\__init__.py", line 319, in loads 3 return _default_decoder.decode(s) 4 File "F:\Python35\lib\json\decoder.py", line 339, in decode 5 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 6 File "F:\Python35\lib\json\decoder.py", line 355, in raw_decode 7 obj, end = self.scan_once(s, idx) 8 json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
而字典轉成列表就僅僅一個items方法就能夠:ip
> goods = {"apple":2,"ipad pro":18} > goods.items() dict_items([('ipad pro', 18), ('apple', 18)])