当前位置: 首页 > news >正文

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

一、 配置文件

1.1 ini

官方-configparser

config.ini文件如下:

 [url] ; section名称baidu = https://www.zalou.cnport = 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.cnport = 80[url.news];搜索网址name = https://www.sina.comport = 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 yamldesired_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)

http://www.lryc.cn/news/410819.html

相关文章:

  • JavaScript基础——JavaScript调用的三种方式
  • ITSS:IT服务工程师
  • 鸿蒙开发——axios封装请求、拦截器
  • Scikit-Learn中的分层特征工程:构建更精准的数据洞察
  • CSOL遭遇DDOS攻击如何解决
  • 基于python的BP神经网络红酒品质分类预测模型
  • Kylin与Spark:大数据技术集成的深度解析
  • ⌈ 传知代码 ⌋ 利用scrapy框架练习爬虫
  • 深入了解 Python 面向对象编程(最终篇)
  • 手把手教你实现基于丹摩智算的YoloV8自定义数据集的训练、测试。
  • SSH相关
  • mysql超大分页问题处理~
  • Gitlab以及分支管理
  • 探索Axure在数据可视化原型设计中的无限可能
  • Redis 内存淘汰策略
  • 逆天!吴恩达+OpenAI合作出了大模型课程!重磅推出《LLM CookBook》中文版
  • uint16_t、uint32_t类型数据高低字节互换
  • Java实现数据库图片上传(包含从数据库拿图片传递前端渲染)-图文详解
  • 开放式耳机原理是什么?通过不入耳的方式,享受健康听音体验
  • 有趣的PHP小游戏——猜数字
  • logstash 全接触
  • Windows本地构建镜像推送远程仓库
  • 计算机毕业设计LSTM+Tensorflow股票分析预测 基金分析预测 股票爬虫 大数据毕业设计 深度学习 机器学习 数据可视化 人工智能
  • 最新版上帝粒子The God Particle(winmac),Cradle Complete Bundle 2024绝对可用
  • 数 据 库
  • 智能城市管理系统设计思路详解:集成InfluxDB、Grafana和MQTTx协议(代码示例)
  • CloseableHttpClient.close() 导致 Connection pool shut down 的问题
  • centos7 docker空间不足
  • C#基于SkiaSharp实现印章管理(5)
  • 【C#】ThreadPool的使用