④ 数据存储
json文件处理
1.json支持的数据格式
字典:使用花括号
数组:使用方括号
整型、浮点型、bool型、null类型
字符串类型:必须用双引号
本质:json就是一个字符串
2.字典和列表转json
# encoding:utf-8
import json
persons = [
{
'username': "xiao",
"age": 20,
"country": "china"
}
]
json_str = json.dumps(persons) //dumps方法转换
print(type(json_str))
print(json_str)
结果:
<class 'str'>
[{"username": "xiao", "age": 20, "country": "china"}]
输出到文件
# encoding:utf-8
import json
persons = [
{
'username': "xiao",
"age": 20,
"country": "china"
}
]
with open('person.json', 'w', encoding='utf-8') as f:
json.dump(persons, f, ensure_ascii=False)
// dump方法存储到文件中
// ensure_ascii=默认为ture 转换为ASCII码,FALSE时需要指定encoding编码
3.将json字符串load成Python对象
# encoding:utf-8
import json
json_str = '[{"username": "小灰灰", "age": 20, "country": "china"}]'
persons = json.loads(json_str) // laods方法
print(type(persons))
for person in persons:
print(person)
从文件读取
# encoding:utf-8
import json
with open('person.json', 'r', encoding='utf-8') as f:
persons = json.load(f) // load方法
print(type(persons))
for person in persons:
print(person)
CSV文件
1.读取csv文件
方法一:
# encoding:utf-8
import csv
with open('stoc.csv', 'r') as f:
next(reader) // 跳过第一行
//reader方法是一个迭代器
reader = csv.reader(f)
for x in reader:
print(x)
方法二:
# encoding:utf-8
import csv
with open('stoc.csv', 'r') as f:
reader = csv.DictReader(f) //返回字典格式,且不会包含第一行
2.写入csv文件
方法一:
# encoding:utf-8
import csv
headers = ['username', 'age', 'height']
values = [
('张三', 18, 180),
('王二', 20, 178),
('李四', 20, 182)
]
with open('test.csv', 'w', encoding='utf-8',newline='') as f:
write = csv.writer(f)
write.writerow(headers) //写入标题
write.writerows(values) //写入多行
方法二:
# encoding:utf-8
import csv
headers = ['username', 'age', 'height']
values = [
{'username': '张三', 'age': 18, 'height': 180},
{'username': '王二', 'age': 20, 'height': 178},
{'username': '李四', 'age': 20, 'height': 182},
]
with open('test.csv', 'w', encoding='utf-8', newline='') as f:
write = csv.DictWriter(f, headers)
write.writeheader() //表头标题需要用writeheader方法
write.writerows(values)