日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 默认配置文件_python各类配置文件写法

發布時間:2025/3/11 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 默认配置文件_python各类配置文件写法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. csv文件

csv:Comma-Separated Values

半結構化數據

逗號分割值,可以使用office或者wps打開。

模塊:csv

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

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

返回一個DictWriter實例。

主要支持的方法有:

writerow,寫入一行

writerows,寫入多行

手動寫入csv文件:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20import csv

from pathlib import Path

row = [4,'tom',22,'home']

rows = [['1','hello'],['22','aaaaaa']]

p = Path('../tmp/mycsv/test.csv')

if not p.parent.exists():

p.parent.mkdir(parents=True)

p.touch()

with open(str(p),'a+') as f:

writer = csv.writer(f)

writer.writerow(row)

writer.writerows(rows)

with open(str(p),'r') as r:

reader = csv.reader(r)

for line in reader:

if line: #去掉空格

print(line)

['4', 'tom', '22', 'home']

['1', 'hello']

['22', 'aaaaaa']

2. ini文件

常見的配置文件格式

configparser 模塊 ConfigParser 類

read(filenames,encoding=None)

sections()返回section列表

add_sections(section_name) 增加一個section

has_sectiones(section_name) 判斷section是否存在

option(section) 返回section的所有option

has_option(section,option) 判斷section是否存在這個option

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

從指定的斷的選項上取值,如果找到就返回,如果沒找到就去拿默認(default)配置信息。

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

寫:

set(section,option,value)

移除:

remove_section(section)

remove_option(section,option)

write(fileobject,space_around_delimiters=True)

將當前的config的所有內容寫入fileobject中,一般open函數使用w模式,space_around_delimiters=True支持等號左右兩側有空格。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34from configparser import ConfigParser

cfg = ConfigParser()

cfg.read('../tmp/ini/php.ini')

print(cfg.sections())

for section in cfg.sections():

for opt in cfg.options(section):

pass

##print(section,opt)

for k,v in cfg.items():

print(k,v)

if not cfg.has_section('test'):

cfg.add_section('test')

#寫入

cfg.set('test','test1','11')

cfg.set('test','tree','i am tree')

with open('../tmp/ini/php.ini','w') as f:

cfg.write(f)

#獲取

a = cfg.get('test','test1')

#默認獲取的為字符串

print(type(a))

print(a)

#明確知道value的值的類型可以直接提取出值,但是如果對應類型錯誤則會報錯

b = cfg.getint('test','test1')

print(type(b))

print(b)

['test']

DEFAULT

test

11

11

總結

以上是生活随笔為你收集整理的python 默认配置文件_python各类配置文件写法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。