使用 python 產生如下面格式的 csv 檔案
id,name,age,tel
1,Allen,20,0981382910
2,Sam,22,0980173952
3,Bob,18,0976975274
4,Daniel,30,0967283712
python 有提供 csv 模組,把它 import 進來.
>>> import csv
定義 header 和 row data
>>> headers = ['id','name','age','tel']
>>> rows = [
{'id' : '1','name' : 'Allen','age' : '20','tel' : '0981382910'},
{'id' : '2','name' : 'Sam','age' : '22','tel' : '0980173952'},
{'id' : '3','name' : 'Bob','age' : '18','tel' : '0976975274'},
{'id' : '4','name' : 'Daniel','age' : '30','tel' : '0967283712'}
]
使用 open 先建立 students.csv 檔案並用,寫入 w 模式,再透過 csv.DictWriter 建立物件,再把 header 和 row data 寫入.
>>> with open('students.csv','w') as f:
... write_csv = csv.DictWriter(f , headers)
... write_csv.writeheader()
... write_csv.writerows(rows)
...
這樣就可以產生一個 students.csv 檔案,如果不要產生 header 只需要 row data 的話,把 write_csv.writeheader 拿掉即可.
> cat students.csv
id,name,age,tel
1,Allen,20,0981382910
2,Sam,22,0980173952
3,Bob,18,0976975274
4,Daniel,30,0967283712
>>> with open('students.csv','r') as f:
... read_csv = csv.reader(f)
... headers = next(read_csv)
... print('headers is {}'.format(headers))
... for row in read_csv:
... for i in range(4):
... print(row[i])
...
headers is ['id', 'name', 'age', 'tel']
1
Allen
20
0981382910
2
Sam
22
0980173952
3
Bob
18
0976975274
4
Daniel
30
0967283712
另一種方式是將 row data 轉成 dictionaries 的方式讀取.
>>> with open('students.csv','r') as f:
... read_csv = csv.DictReader(f)
... for row in read_csv:
... print(row['id'] , row['name'] , row['age'] , row['tel'])
...
1 Allen 20 0981382910
2 Sam 22 0980173952
3 Bob 18 0976975274
4 Daniel 30 0967283712
要處理 json 格式,python json 模組也準備好了,也是 import 進來用.
>>> import json
使用 json.dumps
把 json 格式轉成 json string
>>> data1 = {'id' : '1','name' : 'Allen','age' : '20','tel' : '0981382910'}
>>> data1_json_str = json.dumps(data1)
>>> print(data1_json_str)
{"id": "1", "name": "Allen", "age": "20", "tel": "0981382910"}
透過 json.loads
把 json string 轉成 json data.
>>> data1_json = json.loads(data1_json_str)
>>> print(data1_json)
{'id': '1', 'name': 'Allen', 'age': '20', 'tel': '0981382910'}
如果要產生檔案要使用 json.dump
>>> with open('data1.json','w') as f:
... json.dump(data1,f)
...
產生的檔案
> cat data1.json
{"id": "1", "name": "Allen", "age": "20", "tel": "0981382910"}
一樣透過 json.loads
讀取 json 格式的檔案.
>>> with open('data1.json','r') as f:
... data1 = json.load(f)
... print(data1)
...
{'id': '1', 'name': 'Allen', 'age': '20', 'tel': '0981382910'}
直接給 key 值取得每個 value.
>>> data1['id']
'1'
>>> data1['name']
'Allen'
在使用 json.dumps
有兩個型態的值要注意一下就是 bool 和 None 會被轉換,bool 會被都轉成小寫,而 None 會被轉成 null.
>> data = {'d1': True,'d2': False,'d3':None}
>>> json.dumps(data)
'{"d1": true, "d2": false, "d3": null}'