关于:ini、yaml/yml、excel文件的python操作封装
【代码】关于:ini、yaml/yml、excel文件的python操作封装。
·
python之文件读写、目录操作、序列化str操作后写入文档、xml模块、configparser模块
关于常见文档格式的操作封装

一 .ini文件的操作类
# -*- coding:utf-8 -*-
# @Time: 2021/5/21 11:07
# @Author: 华
# @File: operate_ini.py
# @Software: PyCharm
import data
import configparser
class GetConfig:
"""
封装一个类,进行ini文件的常用操作
"""
def __init__(self, filepath=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
self._path = filepath + r"/data/globalconfig.ini"
print(self._path)
self.config = configparser.ConfigParser() # 实例化解析对象
self.config.read(self._path, encoding='utf-8') # 读文件
def get_sections(self):
"""
获取ini文件所有的块,返回为list
"""
sect = self.config.sections()
return sect
def get_options(self, sec):
"""
获取ini文件指定块的项
:param sec: 传入的块名
:return: 返回指定块的项(列表形式)
"""
return self.config.options(sec)
def get_items(self, sec):
"""
获取指定section的所有键值对
:param sec: 传入的块名
:return: section的所有键值对(元组形式)
"""
return self.config.items(sec)
def get_option(self, sec, opt):
"""
获取指定 小项 的值
:param sec: 传入的块名
:param opt: 传入项
:return: 返回项的值(string类型)
"""
return self.config.get(sec, opt)
def write_(self):
""" 将修改后写入文件 """
with open(self._path, 'w') as fp:
self.config.write(fp)
def add_section_(self, sec):
"""
为ini文件添加新的section, 如果section 已经存在则抛出异常
:param sec: 传入的块名
:return: None
"""
self.config.add_section(sec)
self.write_()
def set_option(self, sec, opt, value):
"""
对指定section下的某个option赋值
:param sec: 传入的块名
:param opt: 传入的项名
:param value: 传入的值
:return: None
"""
self.config.set(sec, opt, value)
self.write_() # 写入文件
def remove_sec(self, sec):
"""
删除某个section
:param sec: 传入的块名
:return: bool
"""
self.config.remove_section(sec)
self.write_() # 写入文件
def remove_opt(self, sec, opt):
"""
删除某个section下的某个option
:param sec: 传入的块名
:param opt: 传入的项名
:return: bool
"""
self.config.remove_option(sec, opt)
self.write_() # 写入文件
二 .yaml文件的操作类
# -*- coding:utf-8 -*-
# @Time: 2021/7/5 10:26
# @Author: 华
# @File: Operation_yaml.py
# @Software: PyCharm
备注:示例的demo.yaml文件:
test:
it:
ot: daihua
# 下面是代码封装
# 注意:
# pip install pyyaml
import yaml
class YamlOperation(dict):
'''继承dict的类,拥有dict的特性'''
def __init__(self, file_path=None, content=None):
super().__init__()
if file_path is not None:
with open(file_path, "r",encoding='UTF-8')as file:
content = yaml.load(file, Loader=yaml.SafeLoader)
# todo: 将yaml文件中读取的所有的key设置为类的属性
content = content if content is not None else {}
for key, value in content.items():
print(key)
print(value)
if isinstance(value, dict):
self[key] = YamlOperation(content=value)
else:
self[key] = value
def __getattr__(self, key):
"""访问不存在的属性key时返回None"""
return None
def __setattr__(self, key, value):
"""设置实例属性值"""
self[key] = value
def __setitem__(self, key, value):
"""给self[key]赋值"""
super().__setattr__(key, value)
super().__setitem__(key, value)
def __missing__(self, key):
"""访问的键key不存在时,返回None"""
return None
if __name__ == '__main__':
import os
data = YamlOperation(os.getcwd()+"/demo.yaml")
print(data.test) # 输出:{'it': {'ot': 'daihua'}}
print(data['test']) # 输出:{'it': {'ot': 'daihua'}}
print(data.get('test')) # 输出:{'it': {'ot': 'daihua'}}
print(data.test.it.ot) # 输出:daihua
print(data.it) # 调用__getattr__ 返回None
print(data['it']) # 调用__missing__ 返回None
三 .excel文件的操作类 (xlrd=1.2.0版本才有好的支持,最新的支持不好)
# -*- coding:utf-8 -*-
# @Time: 2021/5/12 13:44
# @Author: 华
# @File: operate_excel.py
# @Software: PyCharm
import xlrd # 这里的版本==1.2.0才支持.xls
from xlutils.copy import copy
import data
class OperationExcel():
'''
操作excel,获取excel表格中的包括每一个单元格的数据,如:testapi中的url\headers\method
'''
def __init__(self, filepath=data.data_path+"\\interface.xlsx", sheet_id=0):
'''
OperationExcel类初始化,顺带获取了self.data,即:指定sheet的所有数据
:param filepath:数据来源的文件地址
:param sheet_id:excel表单号,sheet_id从0开始
'''
self.filepath = filepath
self.sheet_id = sheet_id
self.data = self.get_data()
def get_data(self):
'''
获取整个sheet表单对象
:return:table,即:表单数据,是一个对象
'''
data = xlrd.open_workbook(self.filepath)
table = data.sheets()[self.sheet_id]
return table
def get_lines(self):
'''
获取sheet的内容所占用的行数
:return:self.lines,行数加入类的属性供全局使用
'''
self.lines = self.data.nrows
return self.lines
def get_cell_value(self, row,column):
'''
获取某一个单元格的内容
:param row: 行数,从0开始
:param column: 列数,从0开始
:return: self.cell_value,单元格值,加入类的属性供全局使用
'''
self.cell_value = self.data.cell_value(row,column)
return self.cell_value
def write_cell_value(self, row,column,value):
'''
写入单元格内容
:param row: 行数,从0开始
:param column: 列数,从0开始
:param value:需要写入的data
:return:None
'''
read_data = xlrd.open_workbook(self.filepath)
write_data = copy(read_data)
sheet_data = write_data.get_sheet(self.sheet_id)
sheet_data.write(row,column,value)
write_data.save(self.filepath)
def get_row_data(self, case_id):
'''
根据caseid,找到对应用例所在行的内容
:param case_id:在本套代码中,即表示excel中的api数据的ID
:return:row_data,用例行数据
'''
row_num = self.get_row_num(case_id)
row_data = self.get_row_values(row_num)
return row_data
def get_row_num(self, case_id):
'''
根据case_id找到对应用例的行的行所在的索引号(行号),
主要方式:循环遍历id列的值,只要等于入参,即返回循环的次数,即为行的index
:param case_id:
:return:
'''
row_num=0
cols_data = self.get_col_data()#默认获取column=0的列数据,return数据为list类型
for col_data in cols_data:
if case_id in col_data:
return row_num
row_num = row_num+1
def get_row_values(self, row):
'''
根据行号row,找到该行的内容
:param row: 行数,从0开始
:return: row_data,行数据,list类型
'''
row_data = self.data.row_values(row)
return row_data
def get_col_data(self, column=0):
'''
根据列column获取某一列的内容
:param column: 列数,从0开始
:return: col_data,列数据,list类型
'''
col_data = self.data.col_values(column)
return col_data
def get_excel_data(self):
'''
获取excel里面的所有的数据,[],ddt的时候使用
:return: <list>
'''
fields_val_list = []
# 这里从index=1开始,因为首行是表头,不是请求数据
for i in range(1,self.get_lines()):
fields_val_list.append(self.get_row_values(i))
return fields_val_list
if __name__ == '__main__':
# 示例:获取默认表单对象
# tab = OperationExcel(sheet_id=1).get_data()
# print(tab)
# 示例:读取非sheet_id=0的单元格数据
dt = OperationExcel(sheet_id=1).get_cell_value(1,1)
print(dt)
四、 pandas 读取excel文件
import pandas as pd
import openpyxl
class OperationExcel():
'''
操作excel,获取excel表格中的包括每一个单元格的数据,如:testapi中的url\headers\method
'''
def __init__(self, filepath=None):
'''
OperationExcel类初始化,顺带获取了self.data,即:指定sheet的所有数据
:param filepath:数据来源的文件地址
:param sheet_id:excel表单号,sheet_id从0开始
'''
self.filepath = filepath
dt = pd.read_excel(self.filepath)
self.df = pd.DataFrame(dt)
def get_rows_data(self, start_row, end_row):
"""
获取多行数据
:return:
"""
return self.df.loc[start_row:end_row]
def get_cell_data(self, row_index, column_name):
"""
获取某个单元格数据
:return:
"""
return self.df.loc[row_index, column_name]
if __name__ == '__main__':
# 示例:获取默认表单对象
# tab = OperationExcel(sheet_id=1).get_data()
# print(tab)
# 示例:读取非sheet_id=0的单元格数据
dt = OperationExcel(filepath=r"D:\project\py_project\cgjgui\data\ele\elex.xls")
# print(dt.get_rows_data(1, 2))
print(dt.get_cell_data(1,"description"))
更多推荐
所有评论(0)