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