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

打印 上一主题 下一主题

主题 1809|帖子 1809|积分 5427

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
一、 配置文件

1.1 ini

官方-configparser
config.ini文件如下:
  1. [url] ; section名称
  2. baidu = https://www.zalou.cn
  3. port = 80
  4. [email]
  5. sender = ‘xxx@qq.com’
复制代码
  1. import configparser
  2. # 读取
  3. file = 'config.ini'
  4. # 创建配置文件对象
  5. con = configparser.ConfigParser()
  6. # 读取文件
  7. con.read(file, encoding='utf-8')
  8. # 取值, 把con当做嵌套字典来用即可
  9. con["url"]
  10. con["url"]["port"]
  11. # 获取所有section
  12. sections = con.sections() # ['url', 'email']
  13. # 获取特定section
  14. items = con.items('url') # 返回结果为元组 # [('baidu','https://www.zalou.cn'),('port', '80')] # 数字也默认读取为字符串
  15. # 可以通过dict方法转换为字典
  16. items = dict(items)
  17. # 写入
  18. import configparser
  19. config = configparser.ConfigParser()
  20. config['DEFAULT'] = {'ServerAliveInterval': '45',
  21.                      'Compression': 'yes',
  22.                      'CompressionLevel': '9'}
  23. config['bitbucket.org'] = {}
  24. config['bitbucket.org']['User'] = 'hg'
  25. config['topsecret.server.com'] = {}
  26. topsecret = config['topsecret.server.com']
  27. topsecret['Port'] = '50022'     # mutates the parser
  28. topsecret['ForwardX11'] = 'no'  # same here
  29. config['DEFAULT']['ForwardX11'] = 'yes'
  30. with open('example.ini', 'w') as configfile:
  31.      config.write(configfile)
复制代码
特殊符号读取

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

  1. [url] ; section名称
  2. [url.search];搜索网址
  3. name = https://www.zalou.cn
  4. port = 80
  5. [url.news];搜索网址
  6. name = https://www.sina.com
  7. port = 80
复制代码
  1. import configparser
  2. con = configparser.ConfigParser()
  3. con.read("test.ini", encoding="utf-8")
  4. print(con.sections()) # ['url', 'url.search', 'url.news']
  5. print(con["url.news"]["name"]) # https://www.sina.com
复制代码
1.2 yaml

官方-pyyaml
Python读写yaml文件
Python基础条记1-Python读写yaml文件(使用PyYAML库)
  1. pip install pyyaml
复制代码
  1. # 写入,字典数据
  2. import yaml
  3. desired_caps = {
  4.     'platformName': 'Android哈哈哈',  # 移动设备系统IOS或Android
  5.     'platformVersion': '7.1.2',  # Android手机系统版本号
  6.     'deviceName': '852',  # 手机唯一设备号
  7.     'app': 'C:\\Users\\wangli\\Desktop\\kbgz-v5.9.0-debug.apk',  # APP文件路径
  8.     'appPackage': 'com',  # APP包名
  9.     'appActivity': 'cui.setup.SplashActivity',  # 设置启动的Activity
  10.     'noReset': 'True',  # 每次运行不重新安装APP
  11.     'unicodeKeyboard': 'True',  # 是否使用unicode键盘输入,在输入中文字符和unicode字符时设置为true
  12.     'resetKeyboard': 'True',  # 隐藏键盘
  13.     'autoGrantPermissions': 'True',
  14.     'autoAcceptAlerts': ["python", "c++", "java"],
  15.     'chromeOptions': {'androidProcess': 'com.tencent.mm:tools'}
  16. }
  17. with open("test1.yaml", "w", encoding="utf-8") as f:
  18.     yaml.dump(desired_caps, f, Dumper=yaml.RoundTripDumper)
  19. # 写入-列表数据
  20. list_data = ['python', 'java', 'c++', 'C#', {'androidProcess': 'com.tencent.mm:tools'}, ["python", "c++", "java"]]
  21. with open("test2.yaml", "w", encoding="utf-8") as f:
  22.     yaml.dump(list_data , f, Dumper=yaml.RoundTripDumper)
  23. # 读取-得到字典
  24. with open('test1.yaml', 'r', encoding='utf-8') as f:
  25.      conf=yaml.load(f.read(),Loader=yaml.Loader) # dict, 和desired_caps 一致
  26. # 读取-得到列表
  27. with open('test2.yaml', 'r', encoding='utf-8') as f:
  28.      conf=yaml.load(f.read(),Loader=yaml.Loader) # list, 和list_data 一致
复制代码
test1.yaml写入后如下
  1. deviceName: '852'
  2. unicodeKeyboard: 'True'
  3. autoAcceptAlerts:
  4. - python
  5. - c++
  6. - java
  7. autoGrantPermissions: 'True'
  8. platformVersion: 7.1.2
  9. platformName: "Android\u54C8\u54C8\u54C8"
  10. app: C:\Users\wangli\Desktop\kbgz-v5.9.0-debug.apk
  11. appPackage: com
  12. chromeOptions:
  13.   androidProcess: com.tencent.mm:tools
  14. appActivity: cui.setup.SplashActivity
  15. noReset: 'True'
  16. resetKeyboard: 'True'
复制代码
test2.yaml写入后如下
  1. - python
  2. - java
  3. - c++
  4. - C#
  5. - androidProcess: com.tencent.mm:tools
  6. - - python
  7.   - c++
  8.   - 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 虽然也被用作配置文件,但更多情况是用来传递数据。
  1. import json
  2. py_data= {
  3.     'no' : 1,
  4.     'name' : 'Runoob',
  5.     'url' : 'http://www.runoob.com'
  6. }
  7. # 写入
  8. with open('data.json', 'w') as fh:
  9.         json_str = json.dumps(py_data)
  10.     fh.write(json_str)
  11. with open('data.json', 'w') as fh:
  12.     json.dump(a, fh)
  13. # 读取
  14. with open("./data.json", "r") as f:
  15.     content = json.load(f)
  16.     print(type(content)) # <class 'dict'>
  17.     print(content)
复制代码
方案1:json模块
方案2:pandas
方案3:dynaconf
其他参考

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

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

莫张周刘王

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表