1)、列表写入:
def write_csv(file_path):
with open(file_path,'w',newline='')as ws:
csv_w = csv.writer(ws)
csv_w.writerow(['001', '12'])
csv_w.writerow(['002':'13'])
2)、字典写入:
def dict_write_csv(file_path):
with open(file_path,'w',newline='')as ws:
finenames = ['name','age','sex']
csv_w = csv.Dictwrite(ws,filenames)
csv_w.wirterow({'name':'张三','age':'12','sex'='男'})
csv_w.wirterow({'name':'李四','age':'13','sex'='男'})
csv_w.wirterow({'name':'王五','age':'14','sex'='男'})
3)、列表读:
def reader_csv(file_path):
with open(file_path,'r')as rs:
csv_r = csv.reader(rs)
for row in csv_r:
print(row)
4)、字典读:
def dict_read_csv(file_path):
with open(file_path,'r')as rs:
csv_r = csv.Dictreader(rs)
for row in csv_r:
print(row)
3、序列化与反序列化:
----------------------------序列化与反序列化的两种方式:json和pickle
1)、json:将数据转为字符串
===============dumps and loads==============
dict = {'a':1,'b':2}
result = json.dumps(dict) ----->字符串
result = json.loads(result) ----->原来的格式
===============dump and load===============
with open('a.txt','w') as ws:
result = json.dump(dict,ws)
with open('b.txt','r')as rs:
content = json.load(rs)
for k,v in content.items():
print(content.get(k))
2)、pickle:把数据持久化到本地磁盘,这部分数据通常只是供系统内部使用
===============dumps and loads==================
pickle.dumps(dict) ----->字节串
pickle.loads(bytes_object) -----> Python类型
===============dump and load ===================
with open('a.txt','w')as ws:
pickle.dump(obj,ws)
with open('a.txt','r')as rs:
pickle.load(rs)