python各类配置文件写法

栏目: Python · 发布时间: 7年前

内容简介:csv:Comma-Separated Values半结构化数据逗号分割值,可以使用office或者wps打开。

csv:Comma-Separated Values

半结构化数据

逗号分割值,可以使用office或者wps打开。

模块:csv

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

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

返回一个DictWriter实例。

主要支持的方法有:

writerow,写入一行

writerows,写入多行

手动写入csv文件:

import 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支持等号左右两侧有空格。

from 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 <Section: DEFAULT>
test <Section: test>
<class 'str'>
11
<class 'int'>
11

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Java核心技术及面试指南

Java核心技术及面试指南

金华、胡书敏、周国华、吴倍敏 / 北京大学出版社 / 2018-9-1 / 59.00

本书根据大多数软件公司对高级开发的普遍标准,为在Java 方面零基础和开发经验在3 年以下的初级程序员提供了升级到高级工程师的路径,并以项目开发和面试为导向,精准地讲述升级必备的技能要点。具体来讲,本书围绕项目常用技术点,重新梳理了基本语法点、面向对象思想、集合对象、异常处理、数据库操作、JDBC、IO 操作、反射和多线程等知识点。 此外,本书还提到了对项目开发很有帮助的“设计模式”和“虚拟......一起来看看 《Java核心技术及面试指南》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具