Py't'hon之csv,ini&序列化,反序列化

 

1.csv文件简介

csv是一个被行分隔符,列分隔符划分成行和列的文本
csv不指定字符编码
行分隔符为\r\n,最后一行可以没有换行符
列分隔符常为逗号和制表符
每一行称之为record

 

from pathlib import Path
p = Path("test.csv")
csv_body = '''\
id,name,age,comment
1,zs,18,"i'm 18"
2,ls,20,"this is a test string"
3,ww,23,"你好"
'''
p.write_text(csv_body)
print("-----------------------------------")
csv_body = '''\
id,name,age,comment
1,zs,18,"i'm 18"
2,ls,20,"this is a test string"
3,ww,23,"你好"
'''
with open('test.csv','w+') as f:
    f.write(csv_body)
print("------------------------------------")

2.csv模块

reader()
返回一个DdictReader对象,是一个行迭代器
delimiter 列分隔符,逗号
lineterminator 行分隔符\r\n
quotechar 字段引用符号,缺省为“。双引号

writer()
返回dictwriter的实例
主要方法有writerow,writerows,writerow(iterable)
import csv
with open('test.csv') as  f:
    reader = csv.reader(f)
    for i in reader:
        print(i)

 

import csv
from pathlib import Path
filename = "test.csv"

csv_body = """id,name,age,comment
1,harden,28,nba player
2,curry,29,mvp
3,james,34,champion
"""

rows = [[4,'durant',29,'Scoring king']]

with open(filename,'a+') as f:
    f.write(csv_body)
    writer=csv.writer(f)
    writer.writerows(rows)


with open(filename,'r+') as r:
    reader = csv.reader(r)
    for i in reader:
        if i:
            print(i)

3.ini文件处理,作为配置文件ini文件很流行

#用来操作ini文件;可以讲section当作key,section存储着键值对组成的字典,可以把ini文件当作一个嵌套的字典,默认使用有序字典
#中括号里面的部分称之为section,没一个section之内,都是key,value形成的键值对,key称为option选项
import configparser
from configparser import ConfigParser

filename = '../Initest.ini'
cfg = ConfigParser()
cfg.read(filename)

for k,v in cfg.items():
    # print(k,cfg.items(k))
    print(k)

 

import json
import configparser
from configparser import ConfigParser

filename = '../Initest.ini'
jsonname = 'jsontest.json'
cfg = ConfigParser()
cfg.read(filename)

dic = {}
for sec in cfg.sections():
    dic[sec] = dict(cfg.items(sec))
print(dic)

with open(jsonname,'w') as f:
    json.dump(dic,f)

 

posted @ 2018-05-22 17:16  亚洲哈登  阅读(585)  评论(0编辑  收藏  举报