您的位置 首页 java

Python常用配置文件ini、json、yaml读写总结

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理

开发项目时,为了维护一些经常需要变更的数据,比如数据库的连接信息、请求的url、测试数据等,需要将这些数据写入配置文件,将数据和代码分离,只需要修改配置文件的参数,就可以快速完成环境的切换或者测试数据的更新,常用的配置文件格式有ini、json、yaml等,下面简单给大家介绍下,Python如何读写这几种格式的文件。

ini格式

ini 即 Initialize ,是Windows中常用的配置文件格式,结构比较简单,主要由节(Section)、键(key)和值(value)组成。每个独立部分称之为section,每个section内,都是key(option)=value形成的键值对。

在Python3中,使用自带的 configparser 库(配置文件解析器)来解析类似于ini这种格式的文件,比如config、conf。

ini读取删除操作

 import configparser
#使用前,需要创建一个实例
config = configparser.ConfigParser()
# 读取并打开文件
config.read('test2.ini',encoding='utf-8')

# 获取sections
print(config.sections())
#['db', 'data']

# 获取某section下的所有options
print(config.options('db'))
#['user', 'pwd', 'host', 'database', 'port']

# 获取某section下指定options
print(config.get('db', 'user'))
# root

# 获取section中所有的键值对
print(config.items('data'))
# [('admin_user', 'tong'), ('admin_pwd', '123456')]

#删除整个section
config.remove_section('db')

#删除section下的某个k
config.remove_option('db','host')
  

ini写入操作

 import configparser

config = configparser.ConfigParser()
config["url"] = {'url':"www.baidu.com"}  #类似于操作字典的形式

with open('example.ini', 'w') as configfile:

    config.write(configfile)  #将对象写入文件
  

json格式

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,这些特性使json成为理想的数据交换语言,易于阅读和编写,同时易于机器解析和生成。关于json的使用,之前写过一篇Python处理json总结,大家可以看下。

json格式示例:

 {
  "name":"smith",
  "age":30,
  "sex":"男"
}
  

Python中使用内置模块 json 操作json数据,使用json.load()和json.dump方法进行json格式文件读写:

 # 读取json
import json
with open('test1.json') as f:
    a = json.load(f)
print(a)

# 写入json
import json
dic ={
    "name" : "xiaoming",
    "age" : 20,
    "phonenumber" : "15555555555"
}

with open("test2.json", "w") as outfile:
    json.dump(dic, outfile)
  

yaml格式

yaml全称Yet Another Markup Language(另一种标记语言),它是一种简洁的非标记语言,以数据为中心,使用空白,缩进,分行组织数据,解析成本很低,是非常流行的配置文件语言。

yaml的语法特点:

  • 大小写敏感
  • 使用缩进表示层级关系,缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • 缩进时不允许使用Tab键,只允许使用空格。
  • 字符串不需要使用引号标注,但若字符串包含有特殊字符则需用引号标注
  • 注释标识为#
  • 开头的行表示构成一个数组

yaml格式示例

 case1:
 info:
  title: "正常登陆"
  url: 
  method: "POST"
 json:
  username: "admin"
  password: "123456"
 expected:
  status_code: 200
  content: "user_id"
  

yaml支持的数据结构有三种:

  • 对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
  • 数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
  • 纯量(scalars):单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、日期

Python中使用 pyyaml 处理yaml格式数据

使用前,需要进行安装

pip install pyyaml

yaml文件读取

用python读取yaml文件,先用open方法读取文件数据,再通过load方法转成字典。

 import yaml
with open("testyaml.yaml", encoding='utf-8') as file:
    data = yaml.safe_load(file)
    print(data)
    print(data['case1']['json'])
    print(data['case1']['json']['username'])
  
 import yaml
#定义一个字典

content = {
    'id': 1,
    'text': 'programming languages',
    'members': ['java', 'python', 'python', 'c', 'go', 'shell']
}

with open('test3.yaml', 'w', encoding='utf-8') as file:
    yaml.dump(content, file, default_flow_style=False, encoding='utf-8', allow_unicode=True)
  

写入的数据带中文,会出现乱码,需要设置allow_unicode=True。

私信小编01即可获取大量Python学习资料

文章来源:智云一二三科技

文章标题:Python常用配置文件ini、json、yaml读写总结

文章地址:https://www.zhihuclub.com/177608.shtml

关于作者: 智云科技

热门文章

网站地图