csv文件
CSV 是一个被行分隔符、列分隔符划分成行和列的文本文件。
CSV 不指定字符编码。
行分隔符为\r\n,最后一行可以没有换行符
列分隔符常为逗号或者制表符。
每一行称为一条记录record
字段可以使用双引号括起来,也可以不使用。如果字段中出现了双引号、逗号、换行符必须使用双引号括起来。如
果字段的值是双引号,使用两个双引号表示一个转义。
表头可选,和字段列对齐就行了。
手动生成csv文件
from pathlib import Path
p = Path('o:/tmp/mycsv/test.csv')
parent = p.parent
if not parent.exists():
parent.mkdir(parents=True)
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)
# 同样可以利用下面的方法写入
with p1.open('w+')as f:
f.write(csv_body)
csv 模块
reader(csvfile, dialect='excel', **fmtparams)
读取CSV内的内容,结果是一个惰性求职的
with p1.open('a',newlines = '')as f:
body = csv.reader(f) # rad er 读取一个可迭代对象
for line in body:
print(line,type(line))
writer(csvfile, dialect='excel', **fmtparams)
返回DictWriter的实例。
主要方法有writerow、writerows。
writerow(iterable)
p = Path('o:/tmp/mycsv/test.csv')
rows = [
[4,'tom',22,'tom'],
(5,'jerry',24,'jerry'),
(6,'justin',22,'just\t"in'),
"abcdefghi",
((1,),(2,))
]
row = rows[0]
with open(str(p), 'a',newlines = '') as f:
writer = csv.writer(f)
writer.writerow(row) # 可以写一行
writer.writerows(rows)# 野=也可以写多行
说明row行,需要一个可迭代对象就可以,可迭代的每一个元素,将作为csv行的每一个元素。
windows下在会在每行末尾多出一个\r,解决办法open(‘test.csv’, ‘w’, newline=’’)
ini文件处理
作为配置文件,ini文件格式的很流行。存文本文件
[DEFAULT]# 缺省section,需要大写
a = test# 中括号里面的部分称为sectiom 译作节,区,段
[mysql]
default-character-set=utf8
[mysqld]
datadir =/dbserver/data
port = 33060
character-set-server=utf8
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
中括号里面的部分称为section,译作节、区、段。
每一个section内,都是key=value形成的键值对,key称为option选项。
注意这里的DEFAULT是缺省section的名字,必须大写。
configparser
configparser模块的ConfigParser类就是用来操作。
可以将section当做key,section存储着键值对组成的字典,可以把ini配置文件当做一个嵌套的字典。默认使用的
是有序字典。
read(filenames, encoding=None)
读取ini文件,可以是单个文件,也可以是文件列表。可以指定文件编码。
sections() 返回section列表。缺省section不包括在内。
add_section(section_name) 增加一个section。
has_section(section_name) 判断section是否存在
options(section) 返回section的所有option,会追加缺省section的option
has_option(section, option) 判断section是否存在这个option
get(section, option, *, raw=False, vars=None[, fallback])
从指定的段的选项上取值,如果找到返回,如果没有找到就去找DEFAULT段有没有。
getint(section, option, *, raw=False, vars=None[, fallback])
getfloat(section, option, *, raw=False, vars=None[, fallback])
getboolean(section, option, *, raw=False, vars=None[, fallback])
上面3个方法和get一样,返回指定类型数据。
items(raw=False, vars=None)
items(section, raw=False, vars=None)
没有section,则返回所有section名字及其对象;如果指定section,则返回这个指定的section的键值对组成二元
组。
set(section, option, value)
section存在的情况下,写入option=value,要求option、value必须是字符串。
import configparser
cfg = configparser.ConfigParser()
cfg.read('d:/tmp/mysql.ini')
read_ok=cfg.read(['d:/tmp/mysql.ini','d:/tmp/123.ini','d:/tmp/t.ini'])
print(read_ok)
>>>['d:/tmp/mysql.ini']# 只有一个读取成功,所以只有一个
print(cfg.sections(),cfg.default_section)
>>>['mysql', 'mysqld'] DEFAULT
################################
print(cfg._sections) # 读取全部的值 #
>>>
OrderedDict([('mysql',
OrderedDict([('default-character-set', 'utf8'), ('a', '1000')])),
('mysqld',
OrderedDict([('datadir', '/dbserver/data'),
('port', '33060'),
('character-set-server', 'utf8'),
('sql_mode',
'NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES')]))])
###################################
for k, v in cfg.items():
print(ty pe(k),k,type(v),v)
>>>
<class 'str'> DEFAULT <class 'configparser.SectionProxy'> <Section: DEFAULT> # section default 是一个section对象
<class 'str'> mysql <class 'configparser.SectionProxy'> <Section: mysql>
<class 'str'> mysqld <class 'configparser.SectionProxy'> <Section: mysqld>
从配置文件中读取 ----get
x = cfg.get('mysql','a')
print(type(x),x)# 如果'a'存在则输出,不存在则取default的值,default 也不存在则出错
y = cfg.get('mysqld','a')
print(type(y),y)
z = cfg.getint('mysqld','a') # 默认返回值都是字符串,可以用getint 形式得到int类型值
print(type(z),z)
w = cfg.get('mysqld','b',fallback = True) # 其中法拉利back的值可以是布尔型,字符串,int 等.输出值相应变形
print(type(w),w)
>>><class 'str'> test
>>><class 'str'> 100
>>><class 'int'> 100
>>><class 'bool'> True
写入配置文件 —set
cfg.set('mysqld','c','True') # 写入的类型必须是字符串类型
写回磁盘
with open ('d:/tmp/mysql.ini','w') as f: # 写回源文件,也可以写的其他文件
cfg.write(f)
print(cfg['mysqld'])
print(cfg['mysqld']['a'])
cfg.add_section('test') # 增加一个section
if cfg.has_section('test'): # 判断是否存在,存在则删除
cfg.remove_section('test')
if cfg.has_option('test','test'): # 判断option是否存在,存在则移除,前提条件是要有队友的section
cfg.remove_option('test02')
cfg['test']={} # 创建一个空的section
cfg['test01']={'test':100} # 创建section
with open('d:/tmp/mysql.ini','w')as f : # 写入
cfg.write(f)