import json
persons = [
{
'username':"蔡",
'age':18
},
{
'username':"时",
'age':19
}
]
with open('person.json','w') as fp:
json.dump(persons,fp,ensure_ascii=False)# json在dump时只能存放ascii字符,所以用ensure_ascii=False关闭这个特性
只有基本数据类型才能转换成JSON格式的字符串,即:int、float、str、list、dict、tuple
import json
with open('person.json','r',encoding='utf-8') as fp:
persons = json.load(fp)
print(type(persons)) #list
for person in persons:
print(person)
import csv
with open('stock.csv','r') as fp:
# reader是迭代器
reader = csv.reader(fp)
next(reader) # 跳过第0行,即不显示标题
for x in reader:
name=x[3]
volumn = x[-1]
print({'name':'name','volumn':volumn})
import csv
with open('stock.csv','r') as fp:
reader= csv.DictReader(fp)
for x in reader:
value = {"name":x['secShortName'],'volumn':x['turnoverVol']}
print(value)
方法①
import csv
headers = ['username','age']
values = [
('张三',18)
('李四',20)
]
# newline去掉每一行中隔的空行
with open('classroom.csv','w',encoding='utf-8',newline='') as fp:
writer = csv.writer(fp)
writer.writerow(headers)
writer.writerrows(values)
方法②
import csv
headers = ['username','age']
values=[
{'username':'张三','age':18},
{'uesername':'李四',‘age’:19}
]
with open('classroom.csv','w',encoding='utf-8',newline='') as fp:
writer=csv.DictWriter(fp,headers)
# 写入表头时要调用writerheader方法
writer.writerheader()
writer.writerows(values)