javascript
Python操作JSON和CSV
JSON
JSON(JavaScript Object Notation, JS 對(duì)象標(biāo)記)是一種輕量級(jí)的數(shù)據(jù)交換格式,易于人閱讀和編寫(xiě),同時(shí)也易于機(jī)器解析和生成,并有效地提升網(wǎng)絡(luò)傳輸效率。
它基于ECMAScript(w3c制定的js規(guī)范)的一個(gè)子集,采用完全獨(dú)立于編程語(yǔ)言的文本格式來(lái)存儲(chǔ)和表示數(shù)據(jù)。簡(jiǎn)潔和清晰的層次結(jié)構(gòu)使得JSON成為理想的數(shù)據(jù)交換語(yǔ)言。
JSON支持?jǐn)?shù)據(jù)格式:
- 對(duì)象(字典)。使用花括號(hào)。
- 數(shù)組(列表)。使用方括號(hào)。
- 整形、浮點(diǎn)型、布爾類(lèi)型還有null類(lèi)型。
- 字符串類(lèi)型(字符串必須要用雙引號(hào),不能用單引號(hào))。
多個(gè)數(shù)據(jù)之間使用逗號(hào)分開(kāi)。注:json本質(zhì)上就是一個(gè)字符串。
JSON函數(shù)
使用JSON函數(shù)需要導(dǎo)入json庫(kù):import json。
| json.dumps | 將Python對(duì)象編碼成JSON字符串 |
| json.loads | 將已編碼的JSON字符串解碼為Python對(duì)象 |
另外:
json.dump()和json.load()主要用來(lái)讀寫(xiě)json文件函數(shù)。
字典和列表轉(zhuǎn)JSON
import jsonbooks = [{'title': 'Python基礎(chǔ)','price': '79.00'},{'title': 'Scrapy網(wǎng)絡(luò)爬蟲(chóng)','price': '56.00'} ]json_str = json.dumps(books) print('type: ', type(json_str)) print('json_str: ', json_str) # 輸出: type: <class 'str'> json_str: [{"title": "Python\u57fa\u7840", "price": "79.00"}, {"title": "Scrapy\u7f51\u7edc\u722c\u866b", "price": "56.00"}]注:因?yàn)閖son在dump的時(shí)候,只能存放ASCII的字符,因此會(huì)將中文進(jìn)行轉(zhuǎn)義,這時(shí)候我們可以使用ensure_ascii=False關(guān)閉這個(gè)特性。
更改之后:
json_str = json.dumps(books, ensure_ascii=False) # 輸出: [{"title": "Python基礎(chǔ)", "price": "79.00"}, {"title": "Scrapy網(wǎng)絡(luò)爬蟲(chóng)", "price": "56.00"}]注:Python中,只有基本數(shù)據(jù)類(lèi)型才能轉(zhuǎn)換成JSON格式的字符串,即:int、float、str、list、dict、tuple。
將json數(shù)據(jù)直接dump到文件中
常規(guī)方式:
''' 遇到問(wèn)題沒(méi)人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書(shū)! ''' import jsonbooks = [{'title': 'Python基礎(chǔ)','price': '79.00'},{'title': 'Scrapy網(wǎng)絡(luò)爬蟲(chóng)','price': '56.00'} ]json_str = json.dumps(books, ensure_ascii=False)with open('books.json', 'w') as fp:fp.write(json_str)打開(kāi)books.json文件發(fā)現(xiàn)出現(xiàn)了亂碼:
[{"title": "Python����", "price": "79.00"}, {"title": "Scrapy��������", "price": "56.00"}]然后指定文件編碼方式:
with open('books.json', 'w', encoding='utf8') as fp:fp.write(json_str)重新打開(kāi)books.json文件發(fā)現(xiàn)一切正常:
[{"title": "Python基礎(chǔ)", "price": "79.00"}, {"title": "Scrapy網(wǎng)絡(luò)爬蟲(chóng)", "price": "56.00"}]json模塊中除了dumps函數(shù),還有一個(gè)dump函數(shù),這個(gè)函數(shù)可以傳入一個(gè)文件指針,直接將字符串dump到文件中。
import jsonbooks = [{'title': 'Python基礎(chǔ)','price': '79.00'},{'title': 'Scrapy網(wǎng)絡(luò)爬蟲(chóng)','price': '56.00'} ]with open('books.json', 'w', encoding='utf8') as fp:json.dump(books, fp) # 輸出: [{"title": "Python\u57fa\u7840", "price": "79.00"}, {"title": "Scrapy\u7f51\u7edc\u722c\u866b", "price": "56.00"}]關(guān)閉中文轉(zhuǎn)義:
with open('books.json', 'w', encoding='utf8') as fp:json.dump(books, fp, ensure_ascii=False) # 輸出: [{"title": "Python基礎(chǔ)", "price": "79.00"}, {"title": "Scrapy網(wǎng)絡(luò)爬蟲(chóng)", "price": "56.00"}]將一個(gè)json字符串load成Python對(duì)象
''' 遇到問(wèn)題沒(méi)人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書(shū)! ''' import jsonjson_str = '[{"title": "Python基礎(chǔ)", "price": "79.00"}, {"title": "Scrapy網(wǎng)絡(luò)爬蟲(chóng)", "price": "56.00"}]' books = json.loads(json_str)print('type: ', type(books)) print('boos: ', books) # 輸出: type: <class 'list'> boos: [{'title': 'Python基礎(chǔ)', 'price': '79.00'}, {'title': 'Scrapy網(wǎng)絡(luò)爬蟲(chóng)', 'price': '56.00'}]直接從文件中讀取json:
import json# 注意指定文件編碼方式 with open('books.json', 'r', encoding='utf8') as fp:json_str = json.load(fp)print(json_str)# 輸出: [{'title': 'Python基礎(chǔ)', 'price': '79.00'}, {'title': 'Scrapy網(wǎng)絡(luò)爬蟲(chóng)', 'price': '56.00'}]csv文件處理
讀取csv文件
import csvwith open('stock.csv','r') as fp:reader = csv.reader(fp)titles = next(reader)for x in reader:print(x)這樣操作,以后獲取數(shù)據(jù)的時(shí)候,就要通過(guò)下表來(lái)獲取數(shù)據(jù)。如果想要在獲取數(shù)據(jù)的時(shí)候通過(guò)標(biāo)題來(lái)獲取。那么可以使用DictReader:
import csvwith open('stock.csv','r') as fp:reader = csv.DictReader(fp)for x in reader:print(x['turnoverVol'])寫(xiě)入數(shù)據(jù)到csv文件
寫(xiě)入數(shù)據(jù)到csv文件,需要?jiǎng)?chuàng)建一個(gè)writer對(duì)象,主要用到兩個(gè)方法。一個(gè)是writerow,這個(gè)是寫(xiě)入一行。一個(gè)是writerows,這個(gè)是寫(xiě)入多行:
''' 遇到問(wèn)題沒(méi)人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書(shū)! ''' import csvheaders = ['name','age','classroom'] values = [('zhiliao',18,'111'),('wena',20,'222'),('bbc',21,'111') ] with open('test.csv','w',newline='') as fp:writer = csv.writer(fp)writer.writerow(headers)writer.writerows(values)也可以使用字典的方式把數(shù)據(jù)寫(xiě)入進(jìn)去。這時(shí)候就需要使用DictWriter了:
import csvheaders = ['name','age','classroom'] values = [{"name":'wenn',"age":20,"classroom":'222'},{"name":'abc',"age":30,"classroom":'333'} ] with open('test.csv','w',newline='') as fp:writer = csv.DictWriter(fp,headers)writer = csv.writeheader()writer.writerow({'name':'zhiliao',"age":18,"classroom":'111'})writer.writerows(values)總結(jié)
以上是生活随笔為你收集整理的Python操作JSON和CSV的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python 回调函数(Callback
- 下一篇: nacos 公共_Springboot,