pandas实现将excel导出到yaml文件中
作者:呆萌的代Ma
这篇文章主要为大家详细介绍了如何使用pandas实现将excel导出到yaml文件中,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
本文介绍了一个将Excel文件转换为YAML格式的工具函数。该工具需要安装pandas和pyyaml库,主要功能包括:读取Excel表格数据,处理空值和日期格式,并将结构化数据输出为YAML文件。
核心函数excel_to_yaml()接收Excel路径、输出YAML路径和可选表名参数,通过pandas读取数据后转换为字典列表,最后使用yaml.dump()写入文件。该工具可方便地将表格数据转换为更适合配置使用的YAML格式。
首先需要安装依赖:
pip install pandas pip install pyyaml
工具函数如下:
import pandas as pd
import yaml
def excel_to_yaml(excel_path, output_yaml_path, excel_sheet_name=0):
"""
将Excel文件转换为YAML文件
:param excel_path: Excel文件路径
:param output_yaml_path: 输出YAML文件路径
:param excel_sheet_name: Excel文件中的表名,默认为0(第一个表)
"""
df = pd.read_excel(excel_path, sheet_name=excel_sheet_name)
data_list = df.to_dict('records')
for record in data_list:
for key, value in record.items():
if pd.isna(value): # 处理空值
record[key] = None
elif hasattr(value, 'strftime'): # 处理日期时间对象
record[key] = value.strftime('%Y-%m-%d')
with open(output_yaml_path, 'w', encoding='utf-8') as yaml_file:
yaml.dump(data_list, yaml_file, allow_unicode=True, sort_keys=False)
def main():
excel_path = "指数列表.xlsx"
output_yaml_path = "out_yaml.yaml"
excel_to_yaml(excel_path, output_yaml_path)
if __name__ == '__main__':
main()
方法补充:
1.Python读取excel内容写入yaml文件
使用Python将Excel文件内容写入YAML文件的过程包括以下几个步骤:
- 使用
openpyxl模块读取Excel文件; - 将Excel表格数据转换成Python对象;
- 将Python对象转换成YAML字符串;
- 将YAML字符串写入YAML文件。
完整代码
import openpyxl
import yaml
xlsx_name = "data.xlsx"
# 打开Excel文件
wb = openpyxl.load_workbook(xlsx_name)
sheet = wb.active
# 读取Excel表格数据并存储为Python对象
data = {'data': []}
for row in sheet.iter_rows(min_row=2, values_only=True):
item = {'name': row[0], 'age': row[1], 'email': row[2]}
data['data'].append(item)
for i in data['data']:
print(i)
# 将Python对象转换成YAML字符串
yaml_data = yaml.dump(data)
# 将YAML字符串写入YAML文件
with open('data.yaml', 'w') as file:
file.write(yaml_data)
# 读取yaml文件内容
with open('data.yaml', 'r') as file:
dataR = yaml.load(file, Loader=yaml.FullLoader)
print(dataR)
'''
{'name': 's1', 'age': 22, 'email': 's1@xcel.com'}
{'name': 's2', 'age': 23, 'email': 's3@xcel.com'}
{'name': '宋', 'age': 24, 'email': 's4@xcel.com'}
{'data': [{'age': 22, 'email': 's1@xcel.com', 'name': 's1'}, {'age': 23, 'email': 's3@xcel.com', 'name': 's2'}, {'age': 24, 'email': 's4@xcel.com', 'name': '宋'}]}
'''2.Python脚本实现将excel 文件中的数据导入yaml文件
这是一个Python脚本,用于将Excel文件转换为YAML格式。脚本读取Excel工作簿中的数据,创建一个有序字典结构,并填充测试用例的相关信息,如类型、名称、描述、路径等。最终,它将这个字典写入YAML文件,实现了测试用例的自动化转换。
import yaml
import os
from collections import OrderedDict
import openpyxl
class TestCases_protocol:
"""This script is to convert excel file to yaml file."""
def __init__(self,file_name,yaml_name):
self.file_name = file_name
self.yaml_name = yaml_name
self.final_dict = OrderedDict()
self.new_pltform_dic = OrderedDict()
def create_dict(self):
wb = openpyxl.load_workbook(self.file_name)
sheet_names = wb.sheetnames
count_cases=[]
for sheet_name in sheet_names:
print(sheet_name)
ws = wb[sheet_name]
max_row = ws.max_row
count_cases.append(max_row-2)
for n_row in range(3,max_row+1):
script_type = ws.cell(row=n_row, column=1).value
script_name = ws.cell(row=n_row, column=2).value
Description = ws.cell(row=n_row, column=3).value
script_path = ws.cell(row=n_row, column=4).value
if not script_type:
continue
else:
self.new_pltform_dic[script_name] = OrderedDict()
self.new_pltform_dic[script_name].update({
"type":script_type,
"loop":'1',
"duration":'60',
"description":Description,
"script_path":script_path,
"parameters": "default"
})
# for k,v in new_pltform_dic.items():
# print(k,':',v)
with open(self.yaml_name, 'w') as f:
yaml.dump(self.new_pltform_dic, f)
print(sum(count_cases))
if __name__=='__main__':
case1 = TestCases_protocol('Test.xlsx','new.yaml')
case1.create_dict()到此这篇关于pandas实现将excel导出到yaml文件中的文章就介绍到这了,更多相关pandas excel导出到yaml内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
