Python中的csv文件

1、csv文件简介:

逗号分隔符Comma—Separated Values。

csv是一个被行分隔符、列分隔符划分为行和列的文本文件。

csv不指定字符编码。

 

行分隔符为\r\n,最后一样可以没有换行符。

列分隔符常为逗号或者制表符。

每一行称为一条记录record。

字段可以使用双引号括起来,也可以不使用。如果字段中出现了双引号,逗号,换行符必须使用双引号括起来。如果字段的值是双引号,使用两个双引号表示一个转义。

2、手动生成csv文件。

代码:

from pathlib import Path

p = Path('test.csv')
parent = p.parent
if not parent.exists():
    parent.makdir( parents =True)

csv_body = '''\
id,name,age,comment
1,zs,18,"im 18"
2,ls,20,"this is a test string"
3,ww,23,"nihao

jisuanji
"
'''
p.write_text(csv_body)

id

name

age

comment

 

 

1

zs

18

im 18

 

 

2

ls

20

this is a test string

 

 

3

ww

23

nihao

jisuanji

 

 

 

 

 

 

 

 

 

表头可选,和字段列对齐就行啦

\须行符。

3、csv模块

reader(csvfile,dialect=’excel’,**fmtparams)

返回DictReader对象,是一个行迭代器。

delimiter列分隔符,逗号

lineterminator行分隔符\r\n

quotechar字段的引用符号,缺省为”,双引号。

 

双引号的处理:

doublequote双引号的处理,默认为True,如果和quotechar为同一个,True则使用两个双引号表示,False表示使用转义字符将作为双引号的前缀。

escapechar一个转义字符,默认为None。

quoting指的双引号的规则,QUOTE_ALL所有字段;QUOTE_MINIMAL特殊字符字段;

QUOTE_NONNUMERIC非数字字段;QUOTE_NONE都不使用引号。

 

writer(csvfile,dialect=’excel’,**fmtparams)

返回Dictwriter实例。

主要方法有writerow、writerows。

Writerow(iterable)

##

import csv
p = Path('test.csv')
parent = p.parent
if not parent.exists():
    parent.makdir( parents =True)

with open(str(p))as f:
    reader = csv.reader(f)
    print(next(reader))
    print(next(reader))

rows = [
    [4,'tom',22,'tom'],
    (5,'jerry',24,'jerry'),
    (6,'justin',22,'just\nin'),
    "abcdefghi",
    ((1,),(2,))
]
row =rows[0]

with open(str(p),'w+')as f:
    writer = csv.writer(f)
    writer.writerow(row)
    writer.writerows(rows)
from pathlib import Path

p = Path('test.csv')
parent = p.parent
if not parent.exists():
    parent.makdir( parents =True)

csv_body = '''\
id,name,age,comment
1,zs,18,"im 18"
2,ls,20,"this is a test string"
3,ww,23,"nihao

jisuanji
"
'''a
import csv
p.parent.mkdir(parents=True,exist_ok=True)
p.write_text(csv_body)

rows = [
    ['4','tom','16','jerry'],
    ['5','zs','18','12'],
    ['6','ls','20','this is '],
    ['7','ww','14','hello'],
    (1,2,3),
    [(1,2,3),(1,2,3)]
]
row = rows[0]
#p = Path(csvname)
if p.is_file():
    with open(str(p),'a',newline='')as f:
        writer = csv.writer(f)
        writer.writerow(row)
        writer.writerows(rows)

 

 

 

 

 

 

 

4、ini文件处理

作为配置文件,ini文件格式很流行。

 

中括号加唯一的名称,名称不得重复。中括号里面的部分称为section,译作节、区、段。

每一个section内,都是key=value行程的键值对,可以称为option选项。

 

注意DEFAULT是缺省section的名字,必须大写。

 

 

1)一为缺省区。

中括号里面的部分成为section,译作节,区、段。

每个section内,都是key,value键值对,key成为option选项。

Default是缺省section,必须大写。

5、Configparser模块

函数或者类后面加括号,调用。

Configparser 模块的ConfigParser类就是用来操作。

可以将section当做key,section存储着键值对形成字典,可以吧ini配置文件当做一个嵌套的字典,默认使用的是有序字典。

read(filenames,encoding=None)

读取ini文件,可以是单个文件,也可以是文件列表,可以指定文件编码。

Sections()返回section列表,缺省section不包括在内。

add_aection(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])

从指定的段的选项上取值,如果找到就返回,没找到就去DEFAULTT段找有没有。

getint(section,option,*,raw=False,Vars=None[,fallback])

getfloat(section,option,*,raw=False,vars=None[,fallback])

getboolean(section,option,*,raw=False,vars=None[,fallback])

三个方法和get一样,返回指定的数据。

Items(raw=False,vars=None)

Items(section,raw=False,vars=None)

没有section,则返回section名字及其对象,如果指定section,则返回这个指定的键值对组成的二元组。

Set(section,option,value)

Sextion存在的情况下,写入option=value,要求option,value必须是字符串。

Remove_section(section)

移除section及其所有的option

Remove_option(section,option)

移除section下的option。

Write(fileobject,space_around_delimiters=True)

将当前的config的所有内容写入到fileobject中,一般open函数使用w模式。

from configparser import ConfigParser

filename = 'test.ini'
newfilename = 'mysql.ini'

cfg = ConfigParser()
cfg.read(filename)
print(cfg.sections())
print(cfg.has_section('client'))

print(cfg.items('mysqld'))
for k,v in cfg.items():
    print(k,type(k))
    print(k,cfg.items(k))

tmp = cfg.get('mysql','port')
print(type(tmp),tmp)
print(cfg.get('mysql','a'))
print(cfg.get('mysqld','magedu',fallback='python'))

tmp =cfg.getint('mysql','port')
print(type(tmp),tmp)

if cfg.has_section('test'):
    cfg.remove_option('test')
cfg.add_section('test')
cfg.set('test','test1','1')
cfg.set('test','test2','2')

with open(newline,'w') as f:
    cfg.write(f)

print(cfg.getint('test','test2'))

cfg.remove_option('test','test2')

print('x'in cfg['test'])
print('x'in cfg['test2'])
print(cfg._dict)

with open(newline,'w')as f:
    cfg.write(f)
posted @ 2018-11-12 22:39  Python爱好者666  阅读(737)  评论(0)    收藏  举报