如何使用Pytest封装读取yaml和ini文件的代码?
- 内容介绍
- 文章标签
- 相关推荐
本文共计314个文字,预计阅读时间需要2分钟。
一、读取YAML和INI文件代码优化+思路:思路:将两个读取文件的代码合并到一个读取文件函数中,避免冗余代码。
优化代码:pythondef read_config(file_path): if file_path.endswith('.yaml'): with open(file_path, 'r') as file: return yaml.safe_load(file) elif file_path.endswith('.ini'): config={} with open(file_path, 'r') as file: for line in file: if line.strip() and not line.startswith('#'): key, value=line.split('=', 1) config[key.strip()]=value.strip() return config else: raise ValueError(Unsupported file format)
一、读取yaml和读取ini代码优化
思路:两个读取文件放到一个读取文件
废话不罗嗦,直接上代码
# -*- coding: UTF-8 -*-
"""
@Project :Pytest
@File :read_data.py
@IDE :PyCharm
@Author :zhou
@Date :2022/8/6 19:05
"""
import configparser
import os
import yaml
# 网址的URL
yaml_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config", "data.yaml")
# 获取settings_ini文件里面的URL
ini_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config", "settings_ini")
class FileRead:
def __init__(self):
self.data_path = yaml_path
self.ini_path = ini_path
def read_data(self):
# 获取文件
f = open(self.data_path, encoding="utf-8")
# 读取文件内容
data = yaml.safe_load(f)
return data
def read_ini(self):
config = configparser.ConfigParser()
config.read(self.ini_path, encoding="utf-8")
return config
base_data = FileRead()
本文共计314个文字,预计阅读时间需要2分钟。
一、读取YAML和INI文件代码优化+思路:思路:将两个读取文件的代码合并到一个读取文件函数中,避免冗余代码。
优化代码:pythondef read_config(file_path): if file_path.endswith('.yaml'): with open(file_path, 'r') as file: return yaml.safe_load(file) elif file_path.endswith('.ini'): config={} with open(file_path, 'r') as file: for line in file: if line.strip() and not line.startswith('#'): key, value=line.split('=', 1) config[key.strip()]=value.strip() return config else: raise ValueError(Unsupported file format)
一、读取yaml和读取ini代码优化
思路:两个读取文件放到一个读取文件
废话不罗嗦,直接上代码
# -*- coding: UTF-8 -*-
"""
@Project :Pytest
@File :read_data.py
@IDE :PyCharm
@Author :zhou
@Date :2022/8/6 19:05
"""
import configparser
import os
import yaml
# 网址的URL
yaml_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config", "data.yaml")
# 获取settings_ini文件里面的URL
ini_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config", "settings_ini")
class FileRead:
def __init__(self):
self.data_path = yaml_path
self.ini_path = ini_path
def read_data(self):
# 获取文件
f = open(self.data_path, encoding="utf-8")
# 读取文件内容
data = yaml.safe_load(f)
return data
def read_ini(self):
config = configparser.ConfigParser()
config.read(self.ini_path, encoding="utf-8")
return config
base_data = FileRead()

