【Python】基础学习&技能提升&代码样例4:常见配置文件和数据文件读写ini、yaml、csv、excel、xml、json

一、 配置文件

1.1 ini

官方-configparser

config.ini文件如下:

 [url] ; section名称
 baidu = https://www.zalou.cn
 port = 80
 [email]
 sender = ‘xxx@qq.com’
import configparser
# 读取
file = 'config.ini'
# 创建配置文件对象
con = configparser.ConfigParser() 
# 读取文件
con.read(file, encoding='utf-8') 
# 取值, 把con当做嵌套字典来用即可
con["url"]
con["url"]["port"]
# 获取所有section
sections = con.sections() # ['url', 'email']
# 获取特定section
items = con.items('url') # 返回结果为元组 # [('baidu','https://www.zalou.cn'),('port', '80')] # 数字也默认读取为字符串
# 可以通过dict方法转换为字典
items = dict(items)

# 写入
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
     config.write(configfile)

特殊符号读取

注意,若配置中有特殊符号,如;或者#在ini的section后是用于注释的,在=后可直接读取进配置中

嵌套配置读取

 [url] ; section名称
 [url.search];搜索网址
 name = https://www.zalou.cn
 port = 80
 [url.news];搜索网址
 name = https://www.sina.com
 port = 80
import configparser
con = configparser.ConfigParser()
con.read("test.ini", encoding="utf-8")
print(con.sections()) # ['url', 'url.search', 'url.news']
print(con["url.news"]["name"]) # https://www.sina.com

1.2 yaml

官方-pyyaml
Python读写yaml文件
Python基础笔记1-Python读写yaml文件(使用PyYAML库)

pip install pyyaml
# 写入,字典数据
import yaml

desired_caps = {
    'platformName': 'Android哈哈哈',  # 移动设备系统IOS或Android
    'platformVersion': '7.1.2',  # Android手机系统版本号
    'deviceName': '852',  # 手机唯一设备号
    'app': 'C:\\Users\\wangli\\Desktop\\kbgz-v5.9.0-debug.apk',  # APP文件路径
    'appPackage': 'com',  # APP包名
    'appActivity': 'cui.setup.SplashActivity',  # 设置启动的Activity
    'noReset': 'True',  # 每次运行不重新安装APP
    'unicodeKeyboard': 'True',  # 是否使用unicode键盘输入,在输入中文字符和unicode字符时设置为true
    'resetKeyboard': 'True',  # 隐藏键盘
    'autoGrantPermissions': 'True',
    'autoAcceptAlerts': ["python", "c++", "java"],
    'chromeOptions': {'androidProcess': 'com.tencent.mm:tools'}
}
with open("test1.yaml", "w", encoding="utf-8") as f:
    yaml.dump(desired_caps, f, Dumper=yaml.RoundTripDumper)

# 写入-列表数据
list_data = ['python', 'java', 'c++', 'C#', {'androidProcess': 'com.tencent.mm:tools'}, ["python", "c++", "java"]]
with open("test2.yaml", "w", encoding="utf-8") as f:
    yaml.dump(list_data , f, Dumper=yaml.RoundTripDumper)

# 读取-得到字典
with open('test1.yaml', 'r', encoding='utf-8') as f:
     conf=yaml.load(f.read(),Loader=yaml.Loader) # dict, 和desired_caps 一致
# 读取-得到列表
with open('test2.yaml', 'r', encoding='utf-8') as f:
     conf=yaml.load(f.read(),Loader=yaml.Loader) # list, 和list_data 一致

test1.yaml写入后如下

deviceName: '852'
unicodeKeyboard: 'True'
autoAcceptAlerts:
- python
- c++
- java
autoGrantPermissions: 'True'
platformVersion: 7.1.2
platformName: "Android\u54C8\u54C8\u54C8"
app: C:\Users\wangli\Desktop\kbgz-v5.9.0-debug.apk
appPackage: com
chromeOptions:
  androidProcess: com.tencent.mm:tools
appActivity: cui.setup.SplashActivity
noReset: 'True'
resetKeyboard: 'True'

test2.yaml写入后如下

- python
- java
- c++
- C#
- androidProcess: com.tencent.mm:tools
- - python
  - c++
  - java

1.3 动态配置读取

用Dynaconf进行Python项目的配置管理
官方-dynaconf

dyanconf的最大特点是用一套代码,从不同的配置数据存储方式中读取配置,例如python配置文件、系统环境变量、redis、ini文件、json文件等等。具体用法参考上面第一个连接,这里不再赘述。

二、 数据文件

不想展开讨论,以下仅列举可读取的方式连接。

1.1 csv

方案1:csv库
方案2:pandas

1.2 excel

方案1:
官方教程openpyxl
Python3使用openpyxl读取和写入excel
方案2:pandas

1.3 xml

xml虽然常被用作配置文件,但他本身的设计是用来存储数据的。
方案1:
xml.dom
xml.dom.minidom
xml.sax
xml.sax.hanldler
xml.sax.reader
xml.etree.ElementTree
方案2:
pandas
xml文件介绍:
XML文件详解(详细易理解)
XML——基本语法及使用规则

1.4 json

json 虽然也被用作配置文件,但更多情况是用来传递数据。

import json
py_data= {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}

# 写入
with open('data.json', 'w') as fh:
	json_str = json.dumps(py_data)
    fh.write(json_str)

with open('data.json', 'w') as fh:
    json.dump(a, fh)

# 读取
with open("./data.json", "r") as f:
    content = json.load(f)
    print(type(content)) # <class 'dict'>
    print(content)

注意,上面的中文会写入文件中,变成unicode编码,如\u5206\u4eab10\u4e2a\u5f88\u5c0f\u4f17。要保证正文写入。可以按照下面方法:

# 写入
with open('data.json', 'w', encoding="utf-8") as fh:
    json.dump(a, fh, ensure_ascii=False)
# 读取
with open("./data.json", "r", encoding="utf-8") as f:
    content = json.load(f)

注意,写入时ensure_ascii=False encoding="utf-8"是必须的。
读取时 encoding="utf-8"是必须的,否则会报错:UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xac in position 123: illegal multibyte sequence

参考

方案1:json模块
方案2:pandas
方案3:dynaconf

其他参考

python读取配置文件方式(ini、yaml、xml)

  • 13
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值