溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

20文件IO_csv_ini

發(fā)布時(shí)間:2020-06-12 03:53:21 來源:網(wǎng)絡(luò) 閱讀:199 作者:chaijowin 欄目:編程語言

?

csv、ini

?

csv

配置信息,ini、xml、json(可映射為dict);

?

結(jié)構(gòu)化:DB,用schema來描述數(shù)據(jù)是干什么的,人可理解;

半結(jié)構(gòu)化:jsonhtml,xml,人可理解;

非結(jié)構(gòu)化:video,image等二進(jìn)制數(shù)據(jù),機(jī)器理解;

?

結(jié)構(gòu)化和半結(jié)構(gòu)化數(shù)據(jù),人可理解;

非結(jié)構(gòu)化數(shù)據(jù),機(jī)器理解;

?

comma separated values,逗號(hào)分隔值;

csv是一個(gè)被行分隔符、列分隔符劃分成行和列的文本文件;

沒有指定的字符編碼,參考RFC 4180 http://www.ietf.org/rfc/rfc4180.txt;

行分隔符為\r\n,最后一行可以沒有換行符;

列分隔符常為逗號(hào)或制表符;

每一行稱為一條record記錄;

字段可以使用雙引號(hào)括起來,也可以不使用;如果字段中出現(xiàn)了雙引號(hào)、逗號(hào)、換行符,必須用雙引號(hào)括起來;如果字段的值是雙引號(hào),使用兩個(gè)雙引號(hào)表示一個(gè)轉(zhuǎn)義(通常一個(gè)特殊字符重復(fù)兩次,表示其本身);

表頭可選,和字段列對(duì)齊就行;

?

20文件IO_csv_ini

?

?

?

csv模塊:

csv.reader(csvfile,dialect='excel',**fmtparams)

**fmtparams,解字典;

返回DictReader的實(shí)例,是個(gè)行迭代器;

delimiter,列分隔符,逗號(hào),也可用:冒號(hào);

lineterminator,行分隔符\r\n;

quotechar,字段的引用符號(hào),缺省為"雙引號(hào),如果使用其它符號(hào),如^,則內(nèi)容中有雙引號(hào)則不用處理;

?

雙引號(hào)的處理:

doublequote,默認(rèn)為True,如果和quotechar為同一個(gè),True則使用2個(gè)雙引號(hào)表示,False表示使用轉(zhuǎn)義字符將作為雙引號(hào)的前綴;

excapechar,一個(gè)轉(zhuǎn)義符,默認(rèn)為None

quoting,指定雙引號(hào)的規(guī)則,QUOTE_ALL所有字段;QUOTE_MINIMAL默認(rèn),特殊字符字段,不沖突不加雙引號(hào),沖突加雙引號(hào);QUOTE_NONNUMERIC,非數(shù)字字段;QUOTE_NONE,都不使用雙引號(hào);

?

csv.writer(csvfile,dialect='excel',**fmtparams),返回DictWriter的實(shí)例,主要方法有csv.write(f).writerow(),csv.write(f).writerows();

?

?

?

例:

s = '''

1,tom,20,

2,jerry,16,

3,,,

'''

?

with open('test.csv','w') as f:

??? for line in s.splitlines():

??????? f.write(line + '\n')

?

In [31]: cat test.csv

?

1,tom,20,

2,jerry,16,

3,,,

?

注:

結(jié)果中第一行為空白,解決辦法:

1

s = '''1,tom,20,

2,jerry,16,

3,,,

'''

2

s = '''\?? #通常用此種

1,tom,20,

2,jerry,16,

3,,,

'''

?

例:

from pathlib import Path

?

p = Path('/home/python/magedu/projects/cmdb/test1/test.csv')

?

parent = p.parent

#print(parent)

?

if not parent.exists():

??? parent.mkdir(parents=True)

?

csv_body = '''\

1,tom,20,

2,jerry,16,

3,jowin,18,

'''

?

p.write_text(csv_body)

?

In [34]: cat test1/test.csv

1,tom,20,

2,jerry,16,

3,jowin,18,

?

例:

from pathlib import Path

import csv

?

path = '/home/python/magedu/projects/cmdb/test.csv'

p = Path(path)

?

if not p.parent.exists():

??? p.parent.mkdir(parents=True)

?

line1 = [1,'tom',20,'']

line2 = [2,'jerry',18,'']

line3 = [line1,line2]

?

with open(path,'w') as f:

??? writer = csv.writer(f)

??? writer.writerow(line1)

??? writer.writerow(line2)

??? writer.writerows(line3)

?

with open(path) as f:

??? reader = csv.reader(f)

??? for line in reader:

??????? if line:

??????????? print(line)

?

?

?

ini文件:

作為配置文件,ini文件格式很流行;

?

例:

]$ egrep -v '^#|^$|[[:space:]]' my.cnf

[client]

[mysqld]

skip-external-locking

log-bin=mysql-bin

binlog_format=mixed

[mysqldump]

quick

[mysql]

no-auto-rehash

[myisamchk]

[mysqlhotcopy]

interactive-timeout

?

中括號(hào)部分稱為section,每一個(gè)section內(nèi),都是key=value形式的kv對(duì),key稱為option選項(xiàng);

字典套字典,配置文件應(yīng)獨(dú)立出來,而不是放在代碼中;

?

configparser模塊的ConfigParser類:

from configparser import ConfigParser

cfg=ConfigParser()

cfg.read(filenames,encoding=None),讀取ini文件,可以是單個(gè)文件(一般僅讀一個(gè)文件),也可以是文件列表,可指定文件編碼;

?

cfg.sections(),返回section列表,缺省section不在內(nèi);

?

cfg.add_section(section_name),增加一個(gè)section;

?

cfg.has_section(section_name),判斷section是否存在;

?

cfg.options(section),返回section的所有option

?

cfg.has_option(section,option),判斷section是否存在這個(gè)option

?

cfg.get(section,option,*,raw=False,vars=None[,fallback]),從指定的段的選項(xiàng)上取值,如果找到返回,如果沒有找到去找DEFAULT段有沒有;

?

cfg.getint(section,option,raw=False,vars=None[,fallback])

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

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

cfg.get()

?

cfg.items(raw=False,vars=None),一般不用,沒有section,則返回所有section名字及其對(duì)象;

?

cfg.items(section,raw=False,vars=None)section存在的情況下,寫入option=value,要求option、value必須是字符串;

?

cfg.remove_section(section),移除section及其所有option;

?

cfg.remove_option(section,option),移除section下的option;

?

cfg.write(fileobject,space_around_delimiters=True),等號(hào)前后有無空格,取默認(rèn)即可;

?

?

?

例:

]$ vim my.cnf

[DEFAULT]

a=test

[mysql]

default-character-set=utf8

[mysqld]

log-bin=mysql-bin

binlog_format=mixed

datadir=/mydata/data

port=3306

character-set-server=utf8

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

In [1]: from configparser import ConfigParser

In [2]: cfg=ConfigParser()

In [3]: cfg.read('my.cnf')

Out[3]: ['my.cnf']

In [4]: cfg.sections()

Out[4]: ['mysql', 'mysqld']

In [5]: cfg.add_section('newsection')

In [6]: cfg.sections()

Out[6]: ['mysql', 'mysqld', 'newsection']

In [9]: cfg.options('mysql')

Out[9]: ['default-character-set', 'a']

In [10]: cfg.options('mysqld')

Out[10]:

['log-bin',

?'binlog_format',

?'datadir',

?'port',

?'character-set-server',

?'sql_mode',

?'a']

In [11]: for section in cfg.sections():

??? ...:???? for option in cfg.options(section):

??? ...:???????? print(section,option)

??? ...:????????

mysql default-character-set

mysql a

mysqld log-bin

mysqld binlog_format

mysqld datadir

mysqld port

mysqld character-set-server

mysqld sql_mode

mysqld a

newsection a

In [12]: cfg.items('mysqld')

Out[12]:

[('a', 'test'),

?('log-bin', 'mysql-bin'),

?('binlog_format', 'mixed'),

?('datadir', '/mydata/data'),

?('port', '3306'),

?('character-set-server', 'utf8'),

?('sql_mode', 'NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES')]

In [13]: for section in cfg.sections():

??? ...:???? for k,v in cfg.items(section):

??? ...:???????? print(section,k,v)

??? ...:????????

mysql a test

mysql default-character-set utf8

mysqld a test

mysqld log-bin mysql-bin

mysqld binlog_format mixed

mysqld datadir /mydata/data

mysqld port 3306

mysqld character-set-server utf8

mysqld sql_mode NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

newsection a test

In [14]: cfg.has_section('newsection')

Out[14]: True

In [15]: if not cfg.has_section('test'):

??? ...:???? cfg.add_section('test')

??? ...:????

In [16]: cfg.sections()

Out[16]: ['mysql', 'mysqld', 'newsection', 'test']

In [17]: cfg.set('test','test1','123')?? #往指定section里添加option=value,'123'是字符,configparser要求的

In [18]: cfg.set('test','test2','abc')

In [19]: cfg.options('test')

Out[19]: ['test1', 'test2', 'a']

In [27]: with open('my.cnf','w') as f:

??? ...:???? cfg.write(f)?? #ini文件更多的是讀取,讀完后常駐內(nèi)存,而不是寫

??? ...:????

In [28]: example=cfg.get('test','test1')

In [29]: type(example)

Out[29]: str

In [30]: example

Out[30]: '123'

In [31]: example1=cfg.getint('test','test1')?? #隱藏有強(qiáng)制類型轉(zhuǎn)換,讀出后是int類型可直接用于計(jì)算

In [32]: example1

Out[32]: 123

In [33]: type(example1)

Out[33]: int

In [34]: example2=cfg.get('test','a') ??#找默認(rèn)段的不是強(qiáng)制的

In [35]: type(example2)

Out[35]: str

In [36]: example2

Out[36]: 'test'

?

?

?

?


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI